django foreign key relation lookup

会有一股神秘感。 提交于 2019-12-10 19:45:23

问题


Given the following models:

class Post(models.Model):
    title = models.CharField(max_length=200)
    html = models.TextField()

class PostTag(models.Model):
    post = models.ForeignKey('Post')
    tag = models.CharField(max_length=200)

I want to accomplish looking up a Post based on a given PostTag. So if I had two posts, A and B, tagged as "foo", I want to be able to look up all posts with that tag and get the posts A and B back.

I image the query would look something like the following:

posts = Post.objects.filter(tag=tag)

Any tips on where to start to accomplish this?


回答1:


Close. You need to specify which field you're spanning across.

Post.objects.filter(posttag__tag=tag)


来源:https://stackoverflow.com/questions/11183081/django-foreign-key-relation-lookup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!