I have 2 models ( Users and Posts )
class Users(models.Model):
email = models.CharField(max_length=225)
class Posts(models.Model):
user = models.ForeignKey(Users, on_delete=models.CASCADE, default=1)
type = models.TextField()
I want to include the user email when getting all posts.
I have done the following but am only getting the user id.
class PostsViewSet(viewsets.ModelViewSet):
serializer_class = PostsSerializer
def get_queryset(self):
queryset = Posts.objects.all()
return queryset
How can I achieve to get the user email within the queryset ?
use https://docs.djangoproject.com/en/4.1/ref/models/querysets/#prefetch-related (not strictly needed, but a good habit) to grab it from the database, use post.user.email to grab the value in code. i.e:
class PostsViewSet(viewsets.ModelViewSet):
serializer_class = PostsSerializer
queryset = Posts.objects.all().prefetch_related("user")
class PostsSerializer(serializers.ModelSerializer):
email = serializers.EmailField(source="user.email")
...
You can annotate the field in the queryset:
from django.db.models import F
class PostsViewSet(viewsets.ModelViewSet):
serializer_class = PostsSerializer
def get_queryset(self):
queryset = Posts.objects.annotate(user_email=F('user__email'))
return queryset
Use all power of serializers. https://www.django-rest-framework.org/api-guide/serializers/
class PostsViewSet(viewsets.ModelViewSet):
serializer_class = PostsSerializer
queryset = Posts.objects.all().prefetch_related("user")
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email')
class PostsSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Post
fields = ('type', 'user')
depth = 1
Related
I am not very professional in django rest...
I wrote a blog with django rest framework and There is no problem when I want to get all the records related to the Article model or get a specific article, for example
But what I want to do is to send an user id(or an user name) to the view when I click on the user's name.
and as a result display all the records of the Article model related to the request.user and all the records of the Article model related to the user whose name was clicked.
In fact, I want to click on the name of each user, in addition to getting the Articles of that user, the Articles related to the request.user will also be taken
This is what I have done so far...
#models.py
class Article(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField
author = models.ForeignKey(User , on_delete = models.CASCADE)
content = models.TextField(null = True)
publish = models.DateTimeField(default = timezone.now)
created = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now = True)
status = models.BooleanField(default = False)
def __str__(self):
return self.title
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
pic = models.ImageField(upload_to="img", blank=True, null=True)
def __str__(self):
return self.user.username
#views.py
class ArticleCreate(CreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleList(ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleDetail(RetrieveUpdateDestroyAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class UserDetail(RetrieveUpdateDestroyAPIView):
queryset = get_user_model().objects.all()
serializer_class = UserSerializer
class UserProfile(RetrieveUpdateDestroyAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
#serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = "__all__"
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = "__all__"
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
exclude = ['updated' , 'created']
You should directly make several modifications in get_queryset() method by using Q objects so:
class ArticleList(ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
def get_queryset(self):
user_id = self.kwargs.get('user_id')
if user_id:
articles = Article.objects.filter(Q(author_id=user_id) | Q(author=self.request.user))
return articles
return self.queryset
You'll also need to modify your urls.py file to include the user_id parameter in the URL so:
from django.urls import path
from .views import ArticleList
urlpatterns = [
path('articles/<int:user_id>/', ArticleList.as_view(), name='article_list'),
# ... Other routes.
]
example URL: http://example.com/api/purchases?username=denvercoder9
class ArticleList(ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
def get_queryset(self):
username = self.request.query_params.get('username')
if username:
return User.objects.filter(username=username).article_set.all()
user = self.request.user
return Article.objects.filter(author=user)
I'm working on a DRF project to learn about ContentType models.
I created a post model and comment model(ContentType) and then added comments to the post. Everything was working fine until I added django-debug-tool and duplicated queries.
I have the following questions:
I've defined a method(children) and property(total_replies) on the comment model. Since total_replies just calling children method and count the size of queryset. Will it result in hitting the database two or more times in case I use the children method in some other methods or property?
If the database is hitting multiple times, what solution two improve performance?
After adding select_related the num of queries has been reduced drastically.
Before using select_related
After using select_related
Is it good to use select_related at all places where Foreignkey has been used?
Blog app
models.py
class Post(models.Model):
title = models.CharField(verbose_name=_("Post Title"), max_length=50)
content = models.TextField()
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='blog_posts')
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.title
#property
def comments(self):
instance = self
#qs = Comment.objects.filter_by_instance(instance) #before
qs = Comment.objects.select_related('user').filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type = ContentType.objects.get_for_model(instance.__class__)
return content_type
serializers.py
class PostSerializer(serializers.ModelSerializer):
author = UserPublicSerializer(read_only=True)
status_description = serializers.ReadOnlyField(source='get_status_display')
class Meta:
model = Post
fields = (
'url', 'id', 'title', 'author',
'content', 'category', 'total_likes',
)
class PostDetailSerializer(serializers.ModelSerializer):
author = UserPublicSerializer(read_only=True)
status_description = serializers.ReadOnlyField(source='get_status_display')
comments = serializers.SerializerMethodField()
class Meta:
model = Post
fields = (
'url', 'id', 'title', 'author', 'content',
'category', 'comments', 'total_likes'
)
def get_comments(self, obj):
request = self.context.get('request')
comments_qs = Comment.objects.filter_by_instance(obj)
comments = CommentSerializer(comments_qs, many=True, context={'request':request}).data
return comments
class PostListCreateAPIView(generics.ListCreateAPIView):
serializer_class = serializers.PostSerializer
# queryset = Post.objects.all().order_by('-id') # before
queryset = Post.objects.select_related('author').order_by('-id')
name = 'post-list'
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save(author=self.request.user)
class PostRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
serializer_class = serializers.PostDetailSerializer
# queryset = Post.objects.all().order_by('-id') # before
queryset = Post.objects.select_related('author').order_by('-id')
name = 'post-detail'
permission_classes = [permissions.IsAuthenticatedOrReadOnly, account_permissions.IsStaffOrAuthorOrReadOnly]
def perform_update(self, serializer):
serializer.save(author=self.request.user)
Comment app
models.py
class CommentManager(models.Manager):
def all(self):
qs = super().filter(parent=None)
return qs
def filter_by_instance(self, instance):
content_type = ContentType.objects.get_for_model(instance.__class__)
object_id = instance.id
qs = super().filter(content_type=content_type, object_id=object_id).select_related('user').filter(parent=None)
return qs
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='comments')
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey(ct_field='content_type', fk_field='object_id')
parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE)
content = models.TextField()
objects = CommentManager()
def __str__(self):
if self.is_parent:
return f"comment {self.id} by {self.user}"
return f"reply {self.id} to comment {self.parent.id} by {self.user}"
def children(self):
return Comment.objects.select_related('user').filter(parent=self)
#property
def is_parent(self):
if self.parent is not None:
return False
return True
#property
def total_replies(self):
return self.children().count()
serializers.py
class CommentSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='comment-detail', lookup_field='pk')
user = UserPublicSerializer(read_only=True)
class Meta:
model = Comment
fields = ('url', 'user', 'id', 'content_type', 'object_id', 'parent', 'content', 'total_replies',)
class CommentChildSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='comment-detail', lookup_field='pk')
user = UserPublicSerializer(read_only=True)
class Meta:
model = Comment
fields = ('url', 'user', 'id', 'content',)
class CommentDetailSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='comment-detail', lookup_field='pk')
replies = serializers.SerializerMethodField()
class Meta:
model = Comment
fields = ('url', 'id', 'content_type', 'object_id', 'content', 'replies', 'total_replies',)
def get_replies(self, obj):
request = self.context.get('request')
if obj.is_parent:
return CommentChildSerializer(obj.children(), many=True, context={'request':request}).data
return None
views.py
class CommentListAPIView(generics.ListCreateAPIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
queryset = Comment.objects.select_related('user').order_by('-id')
name = 'comment-list'
serializer_class = serializers.CommentSerializer
def perform_create(self, serializer):
serializer.save(user=self.request.user)
class CommentDetailAPIView(generics.RetrieveUpdateDestroyAPIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
queryset = Comment.objects.select_related('user').all()
name = 'comment-detail'
serializer_class = serializers.CommentDetailSerializer
def perform_create(self, serializer):
serializer.save(user=self.request.user)
Thanks in advance.
That's exactly what django docs says about select_related :
"Returns a QuerySet that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query. This is a performance booster which results in a single more complex query but means later use of foreign-key relationships won’t require database queries."
They describe select_related as something complex but good in term of transactional db cost.
I have a comment field for every blog post. I want to pass Comment.objects.all() from Views.py to ModelSerializer def get_comments(self, obj) to reduce the number of sql queries. As I am serializing a list of blog posts
Views.py
class BlogViewSet(ModelViewSet):
queryset = Blog.objects.all().annotate(
author_name=F('author__username')
)
serializer_class = BlogSerializer
permission_classes = [IsOwnerOrReadOnly]
def list(self, request):
return Response({'blogs': BlogSerializer(self.queryset, many=True).data})
Serializers.py
class BlogSerializer(ModelSerializer):
author_name = serializers.CharField(read_only=True)
comments = SerializerMethodField()
class Meta:
model = Blog
fields = ('title_text', 'main_text', 'datepublished', 'author_name', 'id', 'comments')
def get_comments(self, obj):
# filter comment
comment_object = Comment.objects.filter(post_id=obj.id)
comments = CommentSerializer(comment_object, many=True).data
return comments
You don't have to pass anything from the View.
First, you have to change the comments field in your BlogSerializer.
class CommentSerializer(ModelSerializer):
# This serializer should have all the details of your comments.
....
class Meta:
model = Comment
fields = "__all__" # Or whatever fields you want to set.
class BlogSerializer(ModelSerializer):
author_name = serializers.CharField(read_only=True)
comments = CommentSerializer(many=True, read_only=True) # I am not sure of the source of your comment reverse manager name
class Meta:
model = Blog
fields = ('title_text', 'main_text', 'datepublished', 'author_name', 'id', 'comments')
Second, you have to make a small change to your view's queryset in order to reduce the number of queries sent to the database by using prefetch_related
class BlogViewSet(ModelViewSet):
queryset = Blog.objects.prefetch_related('comments').all().annotate(
author_name=F('author__username')
)
serializer_class = BlogSerializer
permission_classes = [IsOwnerOrReadOnly]
def list(self, request):
return Response({'blogs': BlogSerializer(self.get_queryset(), many=True).data})
I assumed in the code snippets that you didn't set a related_name on your Blog ForeignKey for the Comment model, so by default, its related manager on Blog will be comment_set
Update
Your models should look like this, in order for this solution to work
class Comment(models.Model):
...
blog = models.ForeignKey('Blog', on_delete=models.CASCADE, related_name='comments')
...
class Blog(models.Model):
# comment = models.ForeignKey(Comment, on_delete=models.CASCADE, null=True)
# this foreign key shouldn't be here, remove it.
....
Do the changes on Serializer and View
# in BlogSerializer
comments = CommentSerializer(many=True, read_only=True)
# In BlogViewSet
queryset = Blog.objects.prefetch_related('comments').all().annotate(
author_name=F('author__username')
)
id field and name field not showing in result.
in models.py:
class Group(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
admin = models.ForeignKey(User, on_delete=models.CASCADE)
member = models.ManyToManyField(User, related_name='groups_user')
def __str__(self):
return self.name
in serializers.py:
class SimpleUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id','first_name', 'last_name')
class GroupSerializer(serializers.Serializer):
admin = SimpleUserSerializer()
class Meta:
model = Group
fields = ('id','name','admin')
views.py:
#api_view(['GET'])
#permission_classes((IsAuthenticated,))
def getSomeGroup(request):
allGroup = Group.objects.all().count()
randomGroupId = random.sample(range(allGroup), 3)
randomGroup = Group.objects.filter(id__in=randomGroupId)
serializer = GroupSerializer(randomGroup, many=True)
#print(serializer)
return Response(serializer.data)
the result comes like this:
[{"admin":{"id":1,"first_name":"asif","last_name":""}},{"admin":{"id":3,"first_name":"Test2","last_name":"lastname"}},{"admin":{"id":3,"first_name":"Test2","last_name":"lastname"}}]
why id and name field not showing?
class SimpleUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
First try to access all admin
#api_view(['GET'])
#permission_classes(IsAuthenticated)
def getSomeGroup(request):
randomGroup = Group.objects.all()
serializer = GroupSerializer(randomGroup, many=True)
return Response(serializer.data)
If that works there may be issue in your these two line
The Issue may be in these two lines
allGroup = Group.objects.all().count()
randomGroupId = random.sample(range(allGroup), 3)
Modify serializers.py:
class GroupSerializer(serializers.ModelSerializer):
I am new to DRF and I want to do something similar to the formsets in django forms
I have an Invoice And Products models related to each other throw a many to many InvoiceDetail model.. when I create an Invoice I choose some products and create a InvoiceDetail object for each .. I want to do this in DRF how can I serialize the Invoice model and it's create function then?
or should i do it form the view?
models.py:
class Invoices(models.Model):
#some fields
products = models.ManyToManyField('Products', through='InvoiceDetail')
class Products(models.Model):
#some fields
class InvoiceDetail(models.Model):
invoice = models.ForeignKey(Invoices, related_name='parent_invoice')
product = models.ForeignKey(Products, related_name='parent_product')
product_description = models.TextField()
product_price = models.DecimalField(max_digits=9, decimal_places=2)
quantity_sold = models.IntegerField()
serializers.py:
class ProductsSerializer(serializers.ModelSerializer):
class Meta:
model = Products
fields = ('barcode', 'product_code', 'name', 'description', 'category',
'quantity_in_stock', 'quantity_on_hold', 'expire_date',
'vendor', 'manufacturer', 'discount')
class InvoiceDetailsSerializer(serializers.ModelSerializer):
class Meta:
model = InvoiceDetail
fields = '__all__'
view.py:
class ProductsView(viewsets.ReadOnlyModelViewSet):
queryset = Products.objects
serializer_class = ProductsSerializer
class InvoicesView(viewsets.ModelViewSet):
queryset = Invoices.objects
serializer_class = InvoicesSerializer
class InvoiceDetailView(viewsets.ModelViewSet):
queryset = InvoiceDetail.objects
serializer_class = InvoiceDetailsSerializer
You could do this in the serializer itself,
class InvoiceSerializer(serializers.ModelSerializer):
products = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all(), many=True)
class Meta:
model = Invoice
fields = [ f.name for f in model._meta.fields ] + ['products']
def create(self, validated_data):
products = validated_data.pop('products')
invoice = super(InvoiceSerializer, self).create(validated_data)
for product in products:
InvoiceDetail.objects.create(invoice=invoice, product=product)
return invoice
This, is just a basic example for to know about how this works. You could customise it however you need.