Django QuerySet返回多个对象(在UNIQUE键上过滤)

时间:2016-04-24 10:07:25

标签: django django-models django-orm django-mysql

我正面临着Django ORM的一个非常奇怪的问题。我有一个下面的queryset,它应该返回单个对象(因为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]

其中qQ()函数的内容:

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出乎意料的行为的想法会有所帮助吗?

0 个答案:

没有答案