简体   繁体   English

django从queryset返回外键对象?

[英]django return foreign key object from queryset?

So I have three models 所以我有三个型号

class Post(....

class Project(....

# have a many to many relationship
class ProjectPost(....
    post = ..... # foreignkey
    project = .... # foreignkey

The data set I want to select is a list of Post objects given a Project object. 我想要选择的数据集是给定Project对象的Post对象列表。

This is what I tried: 这是我试过的:

posts_list = ProjectPost.objects.filter(project=project_object).select_related("post")

But this returns a list of ProjectPost objects rather than a list of Post objects. 但是这会返回ProjectPost对象的列表,而不是Post对象的列表。 What is the correct way of doing this? 这样做的正确方法是什么?

You may want to use the ManyToManyField() 您可能想要使用ManyToManyField()

https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/ https://docs.djangoproject.com/en/dev/topics/db/examples/many_to_many/

You should do it like this: 你应该这样做:

class Post(models.Model):
    pass


class Project(models.Model):
    posts = models.ManyToManyField(Post)

And then, if you want to access the Posts of a Project, you can do 然后,如果您想访问项目的帖子,您可以这样做

project_obj.posts.all()

You can use all the Queryset methods 您可以使用所有Queryset方法

If you want to access the projects of a posts you can do 如果您想访问帖子的项目,您可以这样做

post_obj.project_set.all()

Same as before, you can use all the Queryset methods. 与以前一样,您可以使用所有Queryset方法。

If for any reason you want to do it that way, you could do: 如果出于任何原因你想这样做,你可以这样做:

post_list = ProjectPost.objects.filter(project=project_object).values('post')

Came across this problem myself recently and this was how I solved it. 最近我自己遇到了这个问题,这就是我解决它的方法。 Would love it if someone could comment on whether my solution is efficient. 如果有人可以评论我的解决方案是否有效,那就太喜欢了。

project_posts = ProjectPost.objects.filter(project=project_object).select_related("post")
posts_lists = map(lambda post: project.post, project_posts)

Objects in posts_lists are now of the correct type. posts_lists中的对象现在具有正确的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM