Django rest framework add more data when serialize many object - python

I would like to add an additional field for user's details. But it has to use another value outside of database fields.
For more clearly like this
model:
class User(models.Model):
id= models.AutoField(primary_key=True)
last_name= models.CharField(max_length=20)
first_name=models.CharField(max_length=20)
role_id = models.IntegerField()
serializer:
class UserSerializer(serializers.ModelSerializer):
display_summary = serializers.SerializerMethodField()
login_user_id = serializers.IntegerField(required=False)
class Meta:
model = User
fields = ("id","last_name","first_name", "display_summary", "login_user_id")
def get_display_summary(self, obj):
login_id = self.validated_data.get('login_user_id', None)
login_user = User.objects.filter(pk=login_id).first()
if obj.role_id==2 and login_user.role_id==1:
return 1
return 0
So in my views, when getting just one user, it's all ok:
#api_view(['GET'])
#login_required
def get_user(request, login_user, user_id):
serializer = UserSerializer(User.objects.get(pk=user_id), data={'login_user_id': login_user.id})
if serializer.is_valid():
result = serializer.data
return Response(result, status=status.HTTP_200_OK)
#result:
#{
# "id": 2,
# "last_name": "V",
# "first_name": "Lich",
# "role_id": 2,
# "display_summary": 1
#}
But when I need to return a list, how can I add additional data (login_user_id)?
This is not working:
users = User.objects.filter(last_name__icontains='v')
result_serializer = UserSerializer(users, data={'login_user_id': login_user.id}, many=True)
return result_serializer.data
The error occur say that it's looking for a list, not a dict for inputted param.

Based on #Hai Lang 's idea, I made a new namedtuple to add more info. Something like this:
Serializer:
No use ModelSerializer, use normal Serializer with field I would like to show on this view
class UserSummarySerializer(serializers.Serializer):
user_id = serializers.SerializerMethodField()
last_name = serializers.SerializerMethodField()
first_name = serializers.SerializerMethodField()
display_summary = serializers.SerializerMethodField()
def validate(self, data):
#some validation if needed
return data
def get_user_id(self, obj):
return obj.user.user_id
def get_last_name(self, obj):
return obj.user.last_name
def get_first_name(self, obj):
return obj.user.first_name
def get_display_summary(self, obj):
login_user = obj.login_user
if obj.role_id==2 and login_user.role_id==1:
return 1
return 0
then in my views:
userSummary = namedtuple('userSummary ', ('user', 'login_user'))
users = User.objects.filter(last_name__icontains='v')
objs = [userSummary(u, login_user) for u in users]
result_serializer = UserSerializer(objs, many=True)
return result_serializer.data

Related

how to filter data from two django class

I have two Django class,I want to filter VCDUnavailAudit by site_key in Django Get method, how could I do
enter code here
class VCDUnavailAudit(models.Model):
user_key = models.IntegerField()
user_name = models.CharField(max_length=40)
class User(models.Model):
user_key = models.AutoField(primary_key=True)
site_key = models.IntegerField()
#api_view(['GET'])
def get_unavail_audit_records_by_site(request, site_key: int):
availability_audit_records = VCDUnavailAudit.objects.filter
serializer = VCDUnavailAuditSerializer(availability_audit_records, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
First create a list all user_keys collected from users that have the given site_key.
user_keys = [user.user_key for user in User.objects.filter(site_key=site_key)]
Then get all the availibilty audit records that have their user_key included in the user_keys list.
audits = VCDUnavailAudit.objects.filter(user_key__in=user_keys)
Complete view:
#api_view(['GET'])
def get_unavail_audit_records_by_site(request, site_key: int):
user_keys = [user.user_key for user in User.objects.filter(site_key=site_key)]
audits = VCDUnavailAudit.objects.filter(user_key__in=user_keys)
serializer = VCDUnavailAuditSerializer(audits, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)

update_or_create in my django rest framework api work wrong

My problem in GIF
Instead of updating the user's rating DRF creating new.
Maybe i made a mistake in serializer?
I wrote documentation but i dont kwon where i wrong.
My code:
views.py:
class CreateReviewView(APIView):
def post(self, request):
review = CreateReviewSerializer(data= request.data)
if review.is_valid():
review.save()
return Response(status=201)
class CreateRatingView(APIView):
def get_user(self, request):
user= request.user
if user =="AnonymousUser":
return "noname in CreateRaringView"
return user
def post(self, request):
serializer = CreateRatingSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
serializer.save(user=self.get_user(request))
return Response(status=201)
else:
return Response(status=400)
serializers.py:
class Meta:
model = Rating
fields = ('star','movie')
def new(self,validated_data):
rating = Rating.objects.update_or_create(
user= validated_data.get('user',None),
movie= validated_data.get('movie',None),
defaults={'start': validated_data.get("star")}
)
return rating
models.py:
class Rating(models.Model):
"""Рейтинг"""
user = models.ForeignKey(User,on_delete=models.CASCADE,verbose_name="Пользователь",related_name='user')
star = models.ForeignKey(RatingStar, on_delete=models.CASCADE, verbose_name="Звезда",related_name="star")
movie = models.ForeignKey(Movie, on_delete=models.CASCADE, verbose_name="Фильм",related_name="movie")
def __str__(self):
return f"{self.star} - {self.movie}"
class Meta:
#unique_together = ['user','movie','star']
verbose_name = "Рейтинг"
verbose_name_plural = "Рейтинги"
According to documentation, Calling .save() will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class:
# .save() will create a new instance.
serializer = CommentSerializer(data=data)
# .save() will update the existing `comment` instance.
serializer = CommentSerializer(comment, data=data)
In your case you are only passing new data and missing existing instance.
def post(self, request):
serializer = CreateRatingSerializer(data=request.data)
I renamed def new(self,validated_data): to def create(self,validated_data): in serializers.py and all started working. >.<

DRF- Error when creating a new instance in an M2M through model

I have the following two models:
class User(models.Model):
user_id = models.CharField(
max_length=129,
unique=True,
)
user_article = models.ManyToManyField(
Article,
through="UserArticle",
)
occupation = models.CharField(max_length=100, default='null')
def __str__(self):
return self.user_id
and
class Article(models.Model):
uuid = models.UUIDField(editable=False, unique=True)
company = models.ForeignKey(
Company,
on_delete=models.PROTECT,
related_name='article_company_id',
)
articleType = models.ForeignKey(
ArticleType,
on_delete=models.PROTECT,
related_name='type',
)
date_inserted = models.DateField()
def __str__(self):
return self.uuid
which are modeled with a many-to-many relationship, using this through model:
class UserArticle(models.Model):
user = models.ForeignKey(User, to_field='user_id',
on_delete=models.PROTECT,)
article = models.ForeignKey(Article, to_field='uuid',
on_delete=models.PROTECT,)
posted_as = ArrayField(
models.CharField(max_length=100, blank=True),)
post_date = models.DateField()
class Meta:
db_table = "core_user_articles"
Here's my view:
class BatchUserArticleList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = UserArticle.objects.all()
serializer_class = BatchUserArticleSerializer
def create(self, request, *args, **kwargs):
serializer = BatchUserArticleSerializer(data=request.data)
if not serializer.is_valid():
return response.Response({'Message': 'POST failed',
'Errors': serializer.errors},
status.HTTP_400_BAD_REQUEST)
self.perform_create(serializer) # equal to serializer.save()
return response.Response(serializer.data, status.HTTP_201_CREATED)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
The problem I'm facing is when I want to POST data, of the following format, in the M2M table:
{
"posted_as": ["news"],
"post_date": "2020-05-26",
"user": "jhtpo9jkj4WVQc0000GXk0zkkhv7u",
"article": [
"11111111",
"22222222"
]
}
The above contains a list of many articles so I used a custom field in my serializer in order to extract each article, create a new UserArticle object and insert it, using bulk_create, into my M2M table. I think that's the way to go when the incoming data do not map exactly to the DB model, but I might be wrong. So please comment if you see something off with this approach.
Here is the serializer:
class BatchUserArticleSerializer(serializers.ModelSerializer):
article= ArticleField(source='*') #custom field
class Meta:
model = UserArticle
fields = ('posted_as', 'post_date', 'user', 'article')
def validate(self, data):
post_date = data['post_date']
if post_date != date.today():
raise serializers.ValidationError(
'post_date: post_date is not valid',
)
return data
def create(self, validated_data):
post_as = list(map(lambda item: item, validated_data['posted_as']))
post_date = validated_data['post_date']
user = validated_data['user']
list_of_articles = validated_data['article']
user_object = User.objects.get(user_id=user)
articles_objects = list(map(lambda res: Article.objects.get(uuid=res), list_of_articles))
user_articles_to_insert = list(map(
lambda article: UserArticle(
posted_as=posted_as,
post_date=post_date,
article=article,
user=user_object),
articles_objects))
try:
created_user_articles = UserArticles.objects.bulk_create(user_articles_to_insert)
for res in created_user_articles:
res.save()
return created_user_articles
except Exception as error:
raise Exception('Something went wrong: {0}'.format(error))
and
class ArticleField(serializers.Field):
def to_representation(self, value):
resource_repr = [value.article]
return resource_repr
def to_internal_value(self, data):
internal_repr = {
'article': data
}
return internal_repr
This seems to work ok as I can see data being correctly inserted in the UserArticle table:
id | posted_as | post_date | user | article
1 | news | 2020-05-26 | jhtpo9jkj4WVQc0000GXk0zkkhv7u | 11111111
2 | news | 2020-05-26 | jhtpo9jkj4WVQc0000GXk0zkkhv7u | 22222222
The problem comes when code reaches this line:
response.Response(serializer.data, status.HTTP_201_CREATED)
and more specifically, the error I'm getting is:
AttributeError: Got AttributeError when attempting to get a value for field `posted_as` on serializer `BatchUserArticleSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `list` instance. Original exception text was: 'list' object has no attribute 'posted_as'.
The original exception error is raised at the instance = getattr(instance, attr) line of the def get_attribute(instance, attrs) function in the fields.py DRF source.
What am I missing here?
First of all, there is no reason to call save method for each of bulk-created instances.
Second one is reason of exception. You call create viewset method. it calling serializers create method which must return only one instance (created object). but your serializer returns list created_user_articles. List really have no field posted_as.
So, there is two ways to fix it.
First one is override create method in view, to change the way of data representation. For ex. use another serializer for response data:
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
created_user_articles = self.perform_create(serializer)
# use another way to get representation
response_data = AnotherUserArticleSerializer(created_user_articles, many=True).data
return Response(response_data, status=status.HTTP_201_CREATED, headers=headers)
def perform_create(self, serializer):
# add return to get created objects
return serializer.save()
Second one is return only one instance in create method of your serializer.

Django REST, How to display every 5 element in a response?

Now the serializer displays all the data from the CoinCosts model in response (price,timestamp), but only every 5 element is needed, how to do it? Thanks
I need something like Entry.objects.all()[::5], but I don’t know how to do this with my code.
My code now:
serializers.py
class CoinCostsSerializer(serializers.ModelSerializer):
class Meta:
fields = ('price', 'timestamp')
model = CoinCosts
class CoinSerializer(serializers.ModelSerializer):
class Meta:
fields = ('symbol', 'crr', 'costs')
model = Coins
costs = CoinCostsSerializer(source='filtered_coincosts', many=True)
views.py
class DateTimeGteFilter(filters.IsoDateTimeFilter):
def filter(self, qs, value):
if value != None:
return qs.prefetch_related(Prefetch('coincosts_set', to_attr='filtered_coincosts', queryset=CoinCosts.objects.filter(timestamp__gte=value)
)
)
else:
return qs
class CoinCostFilterSet(filters.FilterSet):
timestamp = DateTimeGteFilter()
class Meta:
model = Coins
fields = {
'symbol': ['exact'],
}
You can use try and except like this in views.py in your def:
try:
obj = Entry.objects.all()[::5]
except IndexError:
obj = None

Return a response with a list of serializers Django REST Framework

I'm coding some backend software for a second-hand selling app using Django and DjangoRestFramework. Right now, I'm trying to send a Response object that contains a list of products, but I seem not to be able to return an actual list of products, as I'm getting an error saying
ListSerializer is not JSON serializable.
I've tried both using the serializer constructor like this:
ProductoSerializer(products, many=True)
And by creating a list of ProductoSerializer.data and then creating the Response object with that.
Here's the serializers that I'm using:
class UserSerializer(serializers.HyperlinkedModelSerializer):
ciudad = serializers.SerializerMethodField()
conectado = serializers.SerializerMethodField()
class Meta:
model = Usuario
fields = ('uid', 'nombre', 'ciudad', 'conectado')
def get_ciudad(self, obj):
geolocator = Nominatim(user_agent="bookalo")
location = geolocator.reverse(str(obj.latitud_registro) + ',' + str(obj.longitud_registro))
return location.raw['address']['city']
def get_conectado(self, obj):
ahora = timezone.now()
result = relativedelta(ahora, obj.ultima_conexion)
return result.days == 0 and result.hours == 0 and result.months == 0 and result.years == 0 and result.minutes < 5
class TagSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Tag
fields = ('nombre')
class MultimediaSerializer(serializers.HyperlinkedModelSerializer):
contenido_url = serializers.SerializerMethodField()
class Meta:
model = ContenidoMultimedia
fields = ('contenido_url', 'orden_en_producto')
def get_contenido_url(self, obj):
return obj.contenido.url
class MiniProductoSerializer(serializers.HyperlinkedModelSerializer):
contenido_multimedia = serializers.SerializerMethodField()
class Meta:
model = Producto
fields = ('nombre', 'precio', 'estado_venta', 'contenido_multimedia')
def get_contenido_multimedia(self, obj):
contenido = ContenidoMultimedia.objects.get(producto=obj.pk, orden_en_producto=0)
return MultimediaSerializer(contenido)
class ProductoSerializer(serializers.HyperlinkedModelSerializer):
vendido_por = UserSerializer(read_only=True)
tiene_tags = TagSerializer(many=True, read_only=True)
contenido_multimedia = serializers.SerializerMethodField()
valoracion_media_usuario = serializers.SerializerMethodField()
class Meta:
model = Producto
fields = ('nombre', 'precio', 'estado_producto', 'estado_venta', 'latitud', 'longitud', 'tipo_envio', 'descripcion', 'vendido_por', 'tiene_tags', 'num_likes', 'contenido_multimedia')
def get_contenido_multimedia(self, obj):
contenido = ContenidoMultimedia.objects.filter(producto=obj.pk).order_by('orden_en_producto')
return MultimediaSerializer(contenido, many=True)
def get_valoracion_media_usuario(self, obj):
return Usuario.objects.get(pk=obj.vendido_por).media_valoraciones
class ValidacionEstrellaSerializer(serializers.HyperlinkedModelSerializer):
usuario_que_valora = UserSerializer(read_only=True)
producto_asociado = serializers.SerializerMethodField()
class Meta:
model = ValidacionEstrella
fields = ('estrellas', 'comentario', 'timestamp', 'usuario_que_valora', 'producto_asociado')
def get_producto_asociado(self, obj):
producto = Producto.objects.get(pk=obj.producto)
return MiniProductoSerializer(producto)
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
usuario_valorado_estrella = serializers.SerializerMethodField()
productos_favoritos = serializers.SerializerMethodField()
class Meta:
model = Usuario
fields = ('uid', 'nombre', 'esta_baneado', 'usuario_valorado_estrella', 'producto_del_usuario')
def get_usuario_valorado_estrella(self, obj):
validaciones = ValidacionEstrella.objects.filter(usuario_valorado=obj.pk).order_by('-timestamp')
return ValidacionEstrellaSerializer(validaciones, many=True, read_only=True)
def get_productos_favoritos(self, obj):
favoritos = Producto.objects.filter(le_gusta_a__in=[obj.pk])
return ProductoSerializer(favoritos, many=True, read_only=True)
class ReportSerializer(serializers.HyperlinkedModelSerializer):
#usuario_reportado = serializers.SerializerMethodField()
usuario_reportado = UserSerializer(read_only=True)
class Meta:
model = Report
fields = ('usuario_reportado', 'causa')
And here's the views.py function that I'm trying to code:
#api_view(['POST'])
#permission_classes((permissions.AllowAny,))
def SearchProduct(request, format=None):
if request.method != 'POST':
return Response(status=status.HTTP_400_BAD_REQUEST)
preposiciones = ['a','ante','bajo','cabe','con','contra','de','desde','en','entre',
'hacia','hasta','para','por','segun','sin','so','sobre','tras']
try:
search = request.POST.get('busqueda')
except:
return Response(status=status.HTTP_404_NOT_FOUND)
products = Producto.objects.none()
for word in search.split():
if word not in preposiciones:
productos_palabra = Producto.objects.filter(nombre__contains=word)
products = products | productos_palabra
products.distinct()
product_list = []
for prod in products:
product_list.append(ProductoSerializer(prod).data)
return Response({'productos': product_list}, status=status.HTTP_200_OK)
I'm using a request object because I also have to server a WebPage, and not only a mobile app, with the same function (the webpage part is still not coded though).
It should return all the products that contain at least one of the words from the user's search, and it all should be structured based on the ProductoSerializer object, but for some reason, it's outputting that error and I'm not quite sure how to fix it.
Thanks in advance, and if you need any extra information which I've missed, please do ask for it... It's been a long day and I probably missed something.
Seems like when you use SerializerMethodField you return serializer instance but not it's data:
For instance:
contenido_multimedia = serializers.SerializerMethodField()
def get_contenido_multimedia(self, obj):
contenido = ContenidoMultimedia.objects.filter(producto=obj.pk).order_by('orden_en_producto')
return MultimediaSerializer(contenido, many=True).data # <-- here try to add .data
It should be changed for all SerializerMethodField methods.

Categories