匹配5个Djang区域中的3个

2024-05-15 03:37:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我觉得这有点棘手!也许有人能帮我

我有以下型号:

class Unicorn(models.Model):

  horn_length = models.IntegerField()
  skin_color = models.CharField()
  average_speed = models.IntegerField()
  magical = models.BooleanField()
  affinity = models.CharField()

我想搜索所有类似的独角兽有至少3个共同领域。你知道吗


是不是太棘手了?还是可行?你知道吗


Tags: modelmodelsmagicallengthclasscolorskincharfield
3条回答

如果我理解正确的话,这应该包括你的问题:

from django.db import models

Unicorn.objects.filter(models.Q(skin_color = 'white') | models.Q(magical = True))

这将过滤所有的独角兽有白色的皮肤或有一些神奇的东西在共同点。更多关于Q对象的信息http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

你应该使用Q对象。粗略的例子是:

from django.db.models import Q
from itertools import combinations
# this -- the unicorn to be matched with
attr = ['horn_length', 'skin_color', 'average_speed', 'magical', 'affinity']
q = None
for c in combinations(attrs, 3):
    q_ = Q(**{c[0]: getattr(this, c[0])}) & Q(**{c[1]: getattr(this, c[1])}) & Q(**{c[2]: getattr(this, c[2])})
    if q is None:
        q = q_
    else:
        q = q | q_
Unicorn.objects.get(q)           

不过,没有经过测试

必须在HAVING子句中完成:

SELECT ... HAVING (IF(a.horn_length=b.horn_length, 1, 0) + ...) >= 3

没有办法在Django ORM中表达HAVING,因此您需要降到raw SQL才能执行它。你知道吗

相关问题 更多 >

    热门问题