9π
β
Serializer makes a database query (not a join, but a separate query)
for each user, to get his/her name.
You can use select_related()
on the queryset
attribute of your view. Then accessing user.name
will not result in further database queries.
class CommentsList(generics.ListAPIView):
serializer_class = CommentListItemSerializer
queryset = Comment.objects.all().select_related('user') # use select_related
I donβt want to have this nested object
"user.name"
. Iβd like to
receive that as a simple string field, for example"username"
You can define a read-only username
field in your serializer with source
argument. This will return a username
field in response.
class CommentListItemSerializer(serializers.ModelSerializer):
# define read-only username field
username = serializers.CharField(source='user.name', read_only=True)
class Meta:
model = Comment
fields = ('username', 'contents', 'rating')
π€Rahul Gupta
3π
You can add custom functions as fields
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.PROTECT, blank=True, null=True)
contents = models.CharField(max_length=510)
rating = models.IntegerField(blank=False, null=False)
def username(self):
return self.user.name
class CommentListItemSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = ('username', 'contents', 'rating')
π€Jose Maeso
- [Django]-No matter what I do, django-admin.py is not found, even though it's in my path
- [Django]-Force reload on client's webpage Django
- [Django]-How to consume XML from RESTful web services using Django / Python?
- [Django]-Django β How to update a field inside a model save() method?
- [Django]-Unable to understand a line from the django tutorial
Source:stackexchange.com