【发布时间】:2019-04-12 07:57:57
【问题描述】:
我有两个模型,一个通过foreign key 与另一个相关,就像这样
class CapturedPrescriptionModel(ColModel):
p_id = models.IntegerField()
p_age = models.IntegerField()
p_gender = models.CharField(max_length=10)
p_care_type = models.CharField(max_length=100)
bacteria_id = models.ForeignKey(BacteriaListModel,
on_delete=models.CASCADE, null=True)
class SuggestedAntibioticsModel(ColModel):
prescription_id = models.ForeignKey(CapturedPrescriptionModel,
related_name='antibiotics',
on_delete=models.CASCADE)
cat_ids = models.TextField()
flag = models.IntegerField(default=0)
现在我想要所有prescriptions 和suggested antibiotics 其中flag=1
我已尝试使用 CapturedPrescriptionModel.objects.filter(antibiotics__flag=1),但它过滤的是处方而不是查询集中的抗生素列表。
[
{
"id": 7,
"p_id": 0,
"p_age": 19,
"p_gender": "Male",
"p_care_type": "ICU",
"bacteria_id": null,
"antibiotics": [
{
"id": 188,
"cat_ids": "[]",
"flag": 0,
"antibiotic_id_id": 87,
"prescription_id_id": 7
},
{
"id": 187,
"cat_ids": "[]",
"flag": 1,
"antibiotic_id_id": 112,
"prescription_id_id": 7
},
......
]
}
....
]
我的预期结果会是这样的
[
{
"id": 7,
"p_id": 0,
"p_age": 19,
"p_gender": "Male",
"p_care_type": "ICU",
"bacteria_id": null,
"antibiotics": [
{
"id": 187,
"cat_ids": "[]",
"flag": 1,
"antibiotic_id_id": 112,
"prescription_id_id": 7
}
]
}
....
]
【问题讨论】:
-
您想要所有处方(即使没有
antibiotics__flag=1的处方),但antibiotics集应该只包含带有flag=1的处方? -
是的,对于那些任何
antibiotics__flag=1都不够用的处方应该是一个空列表
标签: django django-models one-to-many django-orm