我有
class Achievement(MyBaseModel):
pass
class Alias(MyBaseModel):
achievements = models.ManyToManyField('Achievement')
>>> ach = Achievement.objects.all()[1]
这有效:
>>> Alias.objects.all().filter(achievements__pk__contains=ach.pk).count()
77L
但这不是:
>>> Alias.objects.all().filter(achievements__contains=ach).count()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/var/home/ptarjan/django/mysite/django/db/models/query.py", line 489, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/var/home/ptarjan/django/mysite/django/db/models/query.py", line 507, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py", line 1258, in add_q
can_reuse=used_aliases)
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py", line 1201, in add_filter
self.where.add((alias, col, field, lookup_type, value), connector)
File "/var/home/ptarjan/django/mysite/django/db/models/sql/where.py", line 48, in add
params = field.get_db_prep_lookup(lookup_type, value)
File "/var/home/ptarjan/django/mysite/django/db/models/fields/related.py", line 156, in get_db_prep_lookup
raise TypeError, "Related Field has invalid lookup: %s" % lookup_type
TypeError: Related Field has invalid lookup: contains
为什么?(Django 1.0.2)
查看查询日志,它正在做着我没想到的事情!该查询产生:
>>> connection.queries[-1]
{'time': '0.027', 'sql': u'SELECT COUNT(*) FROM `yourock_alias` INNER JOIN `yourock_achiever` ON (`yourock_alias`.`id` = `yourock_achiever`.`alias_id`) WHERE `yourock_achiever`.`achievement_id` LIKE BINARY %j0xvw9% '}
但是这样做
>>> Alias.objects.all().filter(achievements=ach).count()
77L
给出这个查询
>>> connection.queries[-1]
{'time': '0.023', 'sql': u'SELECT COUNT(*) FROM `yourock_alias` INNER JOIN `yourock_achiever` ON (`yourock_alias`.`id` = `yourock_achiever`.`alias_id`) WHERE `yourock_achiever`.`achievement_id` = j0xvw9 '}
这就是我想要的,但在=
我看来,这意味着它是唯一的对象。如果对象在成就列表中的任何位置,django 实际上正在执行的查询正在返回。
这是正确设置并且非常违反直觉还是我做错了什么?