我在 Django ORM 中遇到了一个非常奇怪的问题。我有一个下面的查询集,预计将返回单个对象(作为my_unique_key
唯一值),但它返回同一对象的多个实例(主键检查列表):
my_model_queryset = MyModel.objects.filter(q, obj_key='my_unique_key')
# print my_model_queryset.values_list('id', flat=True)
# [63, 63, 63]
q
内容的Q()
功能在哪里:
some_keys = [u'yJodCsWTTYyi1NMW', u'MOAKea3MSVilbxVU', u'ZXy9ONNQ1MBAMzFT',
u'cuDAuxnAFiuItzDR', u'ZzULRBixdpW9MzC8', u'pYsXxXET0mTPgzl8',
u'C4LmGqhZeILPpgAq', u'gxbkRaMKxySOfkIm']
primary_keys = [6273L, 5974L, 6342L, 4076L, 4490L, 2892L, 3921L, 1554L, 1046L,
5977L, 5946L, 6269L]
q = (Q(cf_object__obj_key__in=some_keys)|
Q(related_my_mapping__cf_object__obj_key__in=some_keys)|
Q(id__in=primary_keys))
我的模型结构如下:
class MyModel(models.Model):
obj_key = models.CharField(max_length=50, unique=True)
cf_object = models.ForeignKey('CFModel', null=True, related_name='related_my_model')
# ...blah...blah...blah...
class Meta:
db_table = 'my_model'
class CFModel(models.Model):
obj_key = models.CharField(max_length=50, unique=True)
# ...blah...blah...blah...
class Meta:
db_table = 'cf_model'
class MyModelCFModelMapping(models.Model):
my_object = models.ForeignKey('MyModel', null=True, related_name='related_my_mapping')
cf_object = models.ForeignKey('CFModel', null=True, related_name='related_my_mapping')
# ...blah...blah...blah...
class Meta:
db_table = 'my_model_cf_model_mapping'
q
但是,如果我从我的函数中删除一个条件,它会很好地工作:
q = (Q(cf_object__obj_key__in=some_keys)|
Q(id__in=primary_keys))
任何关于 Django 行为异常的想法都会有所帮助吗?