我有两个模型类和一个Through类:
class Terms(models.Model):
name = models.CharField(max_length=64)
posts = models.ManyToManyField("Post", through="TermRelation")
class Post(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
published_on = models.DateTimeField(auto_now_add=True)
# Categories and Tags
terms = models.ManyToManyField("Term", through="TermRelation")
class TermRelation(models.Model):
class Meta:
db_table = "tbl_term_relation"
unique_together = (
("term", "term_type", "post"),
)
CITES = (
('CAT', 'Category'),
('TAG', 'Tag'),
)
term = models.ForeignKey(Term, db_column="id_term")
post = models.ForeignKey(Post, db_column="id_post")
term_type = models.CharField('Term Type', max_length=3,
default=CITES[0][0], choices=CITES)
在这里,我只想选择类别Java
中的那些类型的帖子。
所以,我这样做,但这是例外:
Post.objects.filter(terms__name='Java', termrelation_set__term_type='CAT')
正如SQL Expect:
SELECT ... FROM Post p
LEFT OUTER JOIN TermRelation r ON p.id = r.id_post
LEFT OUTER JOIN Term t ON t.id = r.id_term
WHERE r.term_type = 'CAT'
AND t.name = 'Java';
请帮助我,我该怎么办?
答案 0 :(得分:1)
而不是termrelation_set__term_type
,请尝试termrelation__term_type
。从official documentation -
As you are using an intermediate model, you can also query on its attributes:
# Find all the members of the Beatles that joined after 1 Jan 1961
>>> Person.objects.filter(
... group__name='The Beatles',
... membership__date_joined__gt=date(1961,1,1))
[<Person: Ringo Starr]