【问题标题】:query django model with same modelfields使用相同的模型字段查询 django 模型
【发布时间】:2021-11-14 09:17:37
【问题描述】:

所以我有这个 django 模型

class terrain(models.Model):
    location=models.CharField(max_length=200)
    size=models.CharField(max_length=200)
    def __str__(self):
        return str(self.location)

我如何获得具有相同大小的不同地形的位置,我使用了过滤器,但我必须指定大小例如

data=terrain.objects.filter(size="big")

如果不通过传递大小字段来指定大小,我不能这样做

【问题讨论】:

  • link 这是给你的。

标签: django django-models


【解决方案1】:

您需要指定字段。但是有多种过滤方式,您可以在一个字段或多个字段上进行过滤,具体取决于您的要求。

查看文档:django_ filters

【讨论】:

    【解决方案2】:
    terrains = terrain.objects.all()
    data = {}
    
    for terrain in terrains:
        if data.get(terrain.size, None):
            data[terrain.size] = []
        data[terrain.size].append(terrain.location)
    
    print(data) # this will contain all of the locations for different terrain size..
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 2011-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多