代码之家  ›  专栏  ›  技术社区  ›  Rok

按计算(extra())字段筛选

  •  4
  • Rok  · 技术社区  · 15 年前

    有人知道通过extra()方法添加的字段过滤查询集的方法吗?

    例如,这就是我想做的

    _list_items = ListItem.objects.filter(list=1).extra(select=
          'SELECT value AS "type" FROM list_item_optional 
           WHERE list_item_optional.list_optional_id=1 
           AND list_item_optional.list_item_id = list_item.id')
    _list_items = _list_items.filter(type='A')
    

    我知道上面的情况是不允许的,但是在姜戈有什么解决办法呢?

    同样,也不允许使用原始的SQL方法,例如: SELECT fieldA, fieldB, (SELECT blahblah from tableY WHERE id=1) AS "bla" FROM tableX WHERE "bla" = 'x'

    Postgres中不允许按计算字段过滤…有人需要解决吗?由于by sql语句(queryset retrieves)是动态的,并且只在运行时定义,所以问题变得更大。

    干杯

    连接模型:

    class List(models.Model):
        account = models.ForeignKey(Account)
        created_date = models.DateTimeField(auto_now_add=True)
        created_by = models.ForeignKey(AccountUser, related_name='x10')
        updated_date = models.DateTimeField(null=True, blank=True)
        updated_by = models.ForeignKey(AccountUser, null=True, blank=True, related_name='x11')
        is_deleted = models.BooleanField(default=False)
        name = models.CharField(max_length=50)
    
        objects_active = DeletedManager()
    
        class Meta:
            db_table = u'list'
    
    class ListItem(models.Model):
        list = models.ForeignKey(List, db_index=True)
        key = models.CharField(max_length=50)
        name = models.CharField(max_length=100)
    
        class Meta:
            db_table = u'list_item'
            unique_together = ("list", "key")
    
    
    class ListOptional(models.Model):
        list = models.ForeignKey(List, db_index=True)
        name = models.CharField(max_length=50)
        is_searchable = models.BooleanField()
    
        class Meta:
            db_table = u'list_optional'
    
    
    class ListItemOptional(models.Model):
        list_item = models.ForeignKey(ListItem, null=True, db_index=True)
        list_optional = models.ForeignKey(ListOptional, null=True)
        value = models.CharField(max_length=100)
    
        class Meta:
            db_table = u'list_item_optional'
    
    2 回复  |  直到 15 年前
        1
  •  0
  •   Manoj Govindan    15 年前
    SELECT value AS "type" FROM list_item_optional WHERE list_item_optional.list_optional_id=1 AND list_item_optional.list_item_id = list_item.id
    

    这个 WHERE 子句是两个条件的组合: list_item_optional.list_optional_id=1 list_item_optional.list_item_id = list_item.id . 您不能直接应用筛选条件,而不是将其选为额外条件,然后进行筛选吗?我在写这个答案时没有看到有问题的模型。为模型提供源代码会有所帮助。

        2
  •  0
  •   rewritten    15 年前

    试试这个:

    _list_items = ListItem.objects.filter(list=1).extra(select={'type':
        'SELECT value AS "type" FROM list_item_optional '
        'WHERE list_item_optional.list_optional_id=1 '
        'AND list_item_optional.list_item_id = list_item.id')
    _list_items = _list_items.extra(where="`type` = 'A'")
    

    诀窍是使用 extra() where 但在随后的应用中 额外的() 因此构造的查询已经有了新字段。