django外键关系查找 [英] django foreign key relation lookup

查看:101
本文介绍了django外键关系查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下模型:

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)

我想完成查找一个基于给定PostTag。所以如果我有两个帖子,A和B,标记为foo,我想能够查找所有帖子与该标签,并得到A和B的帖子。

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?

推荐答案

关闭。您需要指定您正在跨越哪个字段

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

Post.objects.filter(posttag__tag=tag)

这篇关于django外键关系查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆