【问题标题】:Matching 3 out 5 fields - Django匹配 5 个字段中的 3 个 - Django
【发布时间】:2010-06-03 08:54:34
【问题描述】:

我觉得这有点棘手!也许有人可以帮我解决这个问题

我有以下型号:

class Unicorn(models.Model):

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

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


是不是太难了?或者可行吗?

【问题讨论】:

    标签: python sql-server django django-models django-queryset


    【解决方案1】:

    你应该使用 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)           
    

    虽然没有测试过

    【讨论】:

    • 我的数据库刚刚被删除!开玩笑,测试过了!非常感谢!
    • @Ignacio 好的,我想我明白该怎么做了!谢谢!
    • @RadiantHex 如果这个答案适合你,请选择它
    【解决方案2】:

    必须在HAVING 子句中完成:

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

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

    【讨论】:

    • 谢谢!不过我遇到了一个小问题,因为我经常被要求使用数据库软件。我正在尝试找到一种使用 Django 的 ORM 对其进行抽象的方法。很好的回复,虽然谢谢!
    • HAVING 可在数据库之间移植。是 Django 的 ORM 不支持。
    【解决方案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

    【讨论】:

    • 这个问题合二为一!谢谢! =D
    【解决方案4】:

    我从来没有使用过 Django,而且我是 Python 的新手,但也许你可以这样做:

    创建一个比较 Unicorn 类的两个实例的方法。

    def similarity(self, another)
        sim = 0
        if (self.horn_length==another.horn_length):
            sim+=1
        if (self.skin_color==another.skin_color):
            sim+=1
        if (self.average_speed==another.average_speed):
            sim+=1
        if (self.magical==another.magical):
            sim+=1
        if (self.affinity==another.affinity):
            sim+=1
        return sim
    

    然后您可以使用以下内容进行测试:

    myUnicorn
    for x in unicornsList:
        if myUnicorn.similarity(x) >=3:
            ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      相关资源
      最近更新 更多