简体   繁体   English

使用另一个查询集过滤查询集

[英]Filtering a QuerySet With another QuerySet

Hi i'm not very good at English but i'll try to explain myself the best i could. 嗨,我的英语不太好,但是我会尽力向自己解释。 I'm using python and Django to create a web project. 我正在使用python和Django创建一个Web项目。 I have this 4 models (this is the best translation i can do of the tables and fields): 我有这4个模型(这是我可以对表格和字段进行的最佳翻译):

class Humans (models.Model): 
    name = models.CharField(max_length=15)
    surname = models.CharField(max_length=15)
    doc_num = models.CharField(max_length=11)
    ...

class Records (models.Model): 
    closing_state = models.CharField(max_length=2)
    ...
    humans = models.ManyToManyField(Humans, through='Reco_Huma')

class Reco_Huma (models.Model): 
    id_record = models.ForeignKey(Records)
    id_human = models.ForeignKey(Humans)
    categorys = models.CharField(max_length=2)
    reserv_identity = models.CharField(max_length=2)
    repre_entity = models.CharField(max_length=2)


class Observations (models.Model): 
    id_record = models.ForeignKey(Records)
    text = models.CharField(max_length=80)
    category = models.CharField(max_length=2, choices=CAT)

Now given a doc_num from Humans, a text from Observations i want to get a QuerySet Of all the Records. 现在给定人类的doc_num,来自观察的文本,我想获取所有记录的QuerySet。

To clarify i first do this: 为了澄清我首先这样做:

q1 = Reco_Huma.objects.filter(id_human.doc_num=x)
q2 = Observations.objects.filter(text=y)

both query-sets give me a list of id_record and then i want to connive that lists and filter the Records table with that id_record's 这两个查询集都给我一个id_record的列表,然后我想让该列表与该id_record的Records表一起过滤

I hope you can understand me 希望你能理解我

Thanks in advance 提前致谢

To rephrase your query, you want all the Records associated with a certain Human and which have a certain Observation. 要改写您的查询,您需要与某个特定人员相关且具有特定观察值的所有记录。 So it should be: 所以应该是:

result = Records.objects.filter(observations__text=y, humans__doc_num=x)

As a general rule, if you want to end up with a certain type of object, it helps to start from there in your query. 通常,如果要结束于某种类型的对象,则可以从那里开始查询。

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

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