Django-tables2和Django-filters:过滤字典列表 [英] Django-tables2 and Django-filters: Filtering list of dicts

查看:71
本文介绍了Django-tables2和Django-filters:过滤字典列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子,它是由3种不同的模型制成的.我想过滤它们.但是问题是-我发现的所有示例都是关于queryset的,并且只有一个模型.

I have a table, that I made from 3 different models. And I want to filter them. But the problem is - all examples, that i've found - was about queryset and have only one model.

dict = [
    {'name': Model1.objects.get(id=1), 'adress': Model2.objects.get(id=Model1.objects.get(id=1))}, 
    {'name': Model1.objects.get(id=2),},
    ...
]
filter=FilterSet(queryset=???)

重点是-我从Model1获得的另一个模型的数据.但是我无法在此模型上构建表,因为它没有指向其他2个模型的外键.

The point is - data from another models I got from Model1. But I can't build table on this model, because it don't have foreign keys to other 2 models.

其他词

class Model1(models.Model):
    field1 = models.Charfield()
    field2 = models.Charfield()

class Model2(models.Model):
    field3 = models.Charfield()
    field4 = models.ForeignKey(Model1)
...

有什么建议吗?因为我认为制作另一个模型不是一个好的解决方案.

Any suggestions? Because I don't think that making another model is a good solution.

推荐答案

您可以使用 ForeignKey 创建将两个模型组合在一起的查询集.假设您的模型如下所示(为清楚起见,我将您的FK字段重命名):

You can use the ForeignKey to create a queryset that combines both models. Assume your models look like this (I have renamed your FK field for clarity):

class Model1(models.Model):
    field1 = models.Charfield()
    field2 = models.Charfield()

class Model2(models.Model):
    field3 = models.Charfield()
    model1 = models.ForeignKey(Model1, related_name='model2s')

假设您要搜索所有 field3 为'foo'的 Model2 ,并且使用< bar 的code> field1 .您将按照以下方式进行操作:

Say you wanted to search through all Model2s that had a field3 of 'foo' and were connected to a Model1 with a field1 of bar. You would do this like so:

queryset = Model2.objects.filter(field3='foo', model1__field1='bar')

您也可以使用Django自动创建的 related_name 字段,从 Model1 开始.(如果您未在 ForeignKey 中添加名称,则Django会使用默认的方式来命名这些名称,但始终最好是明确的.)

You could start from Model1 too, using the related_name field that is automagically created by Django. (There is a default way Django will name these if you don't include a name in the ForeignKey, but it's always best to be explicit.)

这将返回任何 Model1 ,其 field1 为'bar'并且与 any Model2 连接的 field3 为'foo'.

This will return any Model1 that has a field1 of 'bar' and is connected to any Model2 with a field3 of 'foo'.

queryset = Model1.objects.filter(field1='bar', model2s__field3='foo')

这篇关于Django-tables2和Django-filters:过滤字典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆