gpt4 book ai didi

django 有没有办法注释嵌套对象?

转载 作者:行者123 更新时间:2023-12-04 04:41:38 25 4
gpt4 key购买 nike

我有以下情况。我有三个模型,Post、User 和 Friends。

class User(models.Model):
name = models.CharField(max_length=100)

class Friend(models.Model):
user1 = models.ForeignKey(User,related_name='my_friends1')
user2 = models.ForeignKey(User,related_name='my_friends2')

class Post(models.Model):
subject = models.CharField(max_length=100)
user = models.ForeignKey(User)

每次带用​​户,都想带上他的好友数:
User.objects.filter(name__startswith='Joe').annotate(fc=Count('my_friends1'))

这工作正常。

但是,当我将用户作为 Post 的嵌套对象时,我想使这项工作。我在那里使用 select_related 来最小化数据库调用,所以我想做一些类似的事情:
Post.objects.filter(subject='sport').select_related('user').annotate(user__fc=Count('user__my_friends1'))

但是,这会在 post 下创建字段 user__fc,而不是在 post.user 下创建字段 fc .
有没有办法实现这个功能?

最佳答案

您可以使用 Prefetch类(class):

from django.db.models import Count, Prefetch

posts = Post.objects.all().prefetch_related(Prefetch('user', User.objects.annotate(fc=Count('my_friends1'))))

for post in posts:
print(post.subject)
print(post.user.fc)
注意:这会执行两个数据库查询(在这种情况下,Django 在 Post 和 User 之间进行连接):
'SELECT "myapp_post"."id", "myapp_post"."subject", "myapp_post"."user_id" FROM "myapp_post"


'SELECT "myapp_user"."id", "myapp_user"."password", "myapp_user"."last_login", "myapp_user"."is_superuser", "myapp_user"."username", "myapp_user"."first_name", "myapp_user"."last_name", "myapp_user"."email", "myapp_user"."is_staff", "myapp_user"."is_active", "myapp_user"."date_joined", COUNT("myapp_friend"."id") AS "fc" FROM "myapp_user" LEFT OUTER JOIN "myapp_friend" ON ("myapp_user"."id" = "myapp_friend"."user1_id") WHERE "myapp_user"."id" IN (3, 4) GROUP BY "myapp_user"."id", "myapp_user"."password", "myapp_user"."last_login", "myapp_user"."is_superuser", "myapp_user"."username", "myapp_user"."first_name", "myapp_user"."last_name", "myapp_user"."email", "myapp_user"."is_staff", "myapp_user"."is_active", "myapp_user"."date_joined"

关于django 有没有办法注释嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16338286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com