首页 > 解决方案 > Django_filters 反向外键关系查找

问题描述

我正在开发一个应用程序,最近试图弄清楚如何在 django 过滤器中使用反向外键关系查找。

模型.py

class Units(models.Model):
    Unit = models.CharField(primary_key=True, max_length=200, null=False, unique=True)
    Type = models.CharField(max_length=200,null=True)
    Floor = models.CharField(max_length=200, null=True)
    Building = models.CharField(max_length=200, null=True)

    def __str__(self):
        return str(self.Unit)

# Keeps track of the inventory updates
class Inventory(models.Model):
    Unit = models.ForeignKey(Units, on_delete=models.CASCADE, null=True, to_field="Unit")
    Price = models.IntegerField(null=True)
    Status= models.CharField(max_length=200, null=True)
    Cancelations_Swaps = models.CharField(max_length=200, null=True)
    Date_of_update = models.DateField(default=timezone.now)
    Custumer = models.ForeignKey('Lead', on_delete=models.CASCADE, null=True, to_field="id")

    def __str__(self):
        return str(self.Unit)

我使用下面的标签在我的模板中显示所有具有最新状态的单元(按更新日期过滤)

@register.filter_function
def fil(i):
    if i.inventory_set.all().order_by('-Date_of_update'):
        status=i.inventory_set.all().order_by('-Date_of_update')[0].Status
        return status
    else:
        return False

模板如下:

模板

{% for i in Unit %}
   <tr>
     <td> {{i.Unit }}</td>
     <td> {{i.Type }}</td>
     <td> {{i.Floor }}</td>
     <td> {{i.Building }}</td>
     <td>{{i|fil}}</td>
   </tr>
{% endfor %}

单位是简单的Units.objects.all()

我还构建了一个过滤器,以过滤显示的数据,如下所示:

class Unitfilter(django_filters.FilterSet):
    class Meta:
        model = Units
        fields = '__all__'
        filter_overrides = {
            models.CharField: {
                'filter_class': django_filters.CharFilter,
                'extra': lambda f: {
                    'lookup_expr': 'icontains',
                },
            }
        }

我希望能够使用最新状态过滤模板,而不仅仅是 Units 模型的字段。你们知道我该怎么做吗?

标签: djangoforeign-keysdjango-filters

解决方案


推荐阅读