匹配 5 个字段中的 3 个 - Django
我觉得这有点棘手!也许有人可以帮助我解决这个问题,
我有以下模型:
class Unicorn(models.Model):
horn_length = models.IntegerField()
skin_color = models.CharField()
average_speed = models.IntegerField()
magical = models.BooleanField()
affinity = models.CharField()
我想搜索所有具有至少 3 个共同字段的类似独角兽。
是不是太刁钻了?或者说是可行的吗?
I'm finding this a bit tricky! Maybe someone can help me on this one
I have the following model:
class Unicorn(models.Model):
horn_length = models.IntegerField()
skin_color = models.CharField()
average_speed = models.IntegerField()
magical = models.BooleanField()
affinity = models.CharField()
I would like to search for all similar unicorns having at least 3 fields in common.
Is it too tricky? Or is it doable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该使用 Q 对象。粗略的例子是:
虽然没有测试过
You should use Q objects. The rough example is:
not tested, though
它必须在
HAVING
子句中完成:在 Django ORM 中无法表达
HAVING
,因此您需要放到 原始 SQL 以便执行它。It has to be done in the
HAVING
clause:There's no way to express
HAVING
in the Django ORM so you'll need to drop to raw SQL in order to perform it.如果我理解正确的话,这应该涵盖您的问题:
这将过滤所有肤色为白色或有一些共同魔法的东西的独角兽。有关 Q 对象的更多信息,请参见此处 http ://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
This should cover your question, if I understood it right:
This would filter all unicorns that have skin color white or have some magical stuff in common. More about the Q objects here http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
我从未使用过 Django,而且我在 Python 方面相当新手,但也许你可以做这样的事情:
创建一个方法来比较 Unicorn 类的两个实例。
然后你可以用类似的东西进行测试:
I have never used Django and i'm rather novice in Python but perhaps you can do something like this:
make a method that compares two instances of the class Unicorn.
Then you can test with something like: