django - 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 模型的字段。你们知道我该怎么做吗?
解决方案
推荐阅读
- django - Django 是否缓存数据库的 DNS 信息?
- java - 如何知道新文件是否添加到谷歌驱动器中的特定文件夹
- javascript - 如何仅突出显示 HTML 元素的某些单词?
- python - 将具有多个时区的 pandas 列转换为单个时区
- javascript - Firefox 不能一次下载多个文件?
- python-3.x - 从列表中获取子列表的组合
- python - 如何在fabric 2.4中指定远程shell
- php - 替换字符串中的枕头
- c# - 如何获得语音识别来检测 SAPI 强调标记?
- button - 如果表单上只有一个单选按钮,则默认检查 PrimeNG-radiobutton