查询RelatedManager对象

时间:2018-10-09 09:21:33

标签: python django django-queryset django-related-manager

我有

之类的模型
payload.Payload.bubble.success

我的payload.Payload.bubble.progress

class Model1(models.Model):
    f1 = models.DateField(null=True, blank=True)
    f2 = models.CharField(max_length=100,null=True, blank=True)
    f3 = models.CharField(max_length=100,null=True, blank=True)

class Model2(models.Model):
    x = models.ForeignKey(Model1)
    f4 = models.CharField(null=True, blank=True)
    f5 = models.CharField(max_length=100,null=True, blank=True)

我希望根据字段admin.py的特定值过滤Model1

类似

class Model2Inline(admin.TabularInline): model = Model2 search_fields = ('f5',) extra = 1 class Model1Admin(admin.ModelAdmin): list_display = ('f1', 'f2') search_fields = ['f1'] inlines = [Model2Inline]

旨在产生一个包含Model1实例的查询集,其中内联Model2的f4设置为results = Model1.objects.filter(where f4 = "some_specific_value")

谢谢!

1 个答案:

答案 0 :(得分:0)

这应该可以工作(编辑,感谢@DanielRoseman指出了我所缺少的内容):

results = Model1.objects.filter(model2_set__f4="some_specific_value")

您还可以为ForeignKey属性指定一个related_name关键字参数,以便您可以使用比Model2更易懂的名称来引用Model1中的model2_set

请参阅https://docs.djangoproject.com/en/2.1/topics/db/queries/#related-objects上的文档