I have Django models as shown below,i need to make a view in which i have to get post.id,post.title,post.description,owner.name,number of likes for that post id.how to make a single query for getting all these details?.any suggestions?
class Post(models.Model):
title=models.CharField(max_length=150)
description=models.TextField()
owner=models.ForeignKey("User")
class User(models.Model):
name=models.CharField(max_length=200)
location=models.CharField(max_length=200)
class comment(models.Model):
post_id=models.ForeignKey("Post", null=True,blank=True)
user_id=models.ForeignKey("USER")
// #likes may be for post or for comment
class likes(models.Model):
post_id=models.ForeignKey("Post", null=True,blank=True)
comment_id=models.ForeignKey("comment", null=True,blank=True)
user_id=models.ForeignKey("USER")
You can use select_related to join the User model in a single query, and annotate to count the likes for a given post:
from django.db.models import Count
my_id = 42
post = Post.objects.select_related('owner') \
.annotate(num_likes=Count('likes')) \
.get(id=my_id)
You can then access the values:
post.id
post.title
post.description
post.owner__name
post.num_likes
这里的 id 只是一个条目,但是我们有多个条目,例如 20,50 等,例如在我的情况下,条目是 2000,我怎样才能运行此代码 2000 次
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.