【问题标题】:Filter across three tables using django ORM使用 django ORM 过滤三个表
【发布时间】:2019-07-05 14:48:48
【问题描述】:

我有 3 个 django 模型,其中第二个对第一个有外键,第三个对第一个有外键。像这样:

    NewRegistration Model

    class NewRegistration(models.Model):
            registration_date = models.DateField()
            ward_no = models.ForeignKey(system_settings.models.Wardno)
            latitude = models.DecimalField(decimal_places=16, max_digits=30)
            longitude = models.DecimalField(decimal_places=16, max_digits=30)
            is_forwarded = models.BooleanField(default=False)
    Landowner Model

    class Landowner(models.Model):
        lo_address_roadname_en = models.TextField(max_length=100, null=True, blank=True)
        reg = models.ForeignKey(NewRegistration)
    Application  model

    class Application(models.Model):
        building_storey = models.IntegerField(blank=True, null=True, default=0)
        reg = models.ForeignKey(NewRegistration) 

我想根据 no_of_storey 有来自 Landowner 模型的某些 lo_address_roadname_en 和来自 NewRegistration 模型的某些 ward_no 以及来自 NewRegistration 模型的某些 registration_date 来计算申请表的数据 我试过这样。

 building_storey = Application.objects.filter(reg__ward_no=ward_no).filter(reg__registration_date__gte=start_date,reg__registration_date__lte=end_date).values('building_storey').annotate(Count('building_storey'))
            context['building_storey'] = building_storey

如何从三个表中筛选?请帮帮我。

【问题讨论】:

    标签: django


    【解决方案1】:
    NewRegistration.objects.filter(
          registration_date__gt=${date},
          Landowner__lo_address_roadname_en=${lo_address_value},
          ward_no=${ward_no},
    ).values('Application__building_storey')
    

    这是您可以从 3 个表中过滤值的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 2010-11-04
      • 2016-12-09
      • 2020-06-06
      • 2014-09-24
      • 2021-10-01
      • 2016-04-22
      相关资源
      最近更新 更多