2013-07-08 57 views
2

我有一个模型,指向一个通用关系。这可以是联系对象或客户对象。通用关系上的Django过滤器

class Unsubscribe(models.Model): 
    """ 
    Notes: 
    See: http://www.screamingatmyscreen.com/2012/6/django-and-generic-relations/ 
    """ 
    content_type = models.ForeignKey(ContentType, help_text="Represents the name of the model") 
    object_id = models.PositiveIntegerField(help_text="stores the object id") 
    content_object = generic.GenericForeignKey('content_type', 'object_id') 

    reason = models.CharField(max_length=60) 

    request_made = models.DateTimeField(auto_now_add=True, 
            help_text="Shows when object was created.") 


    class Meta: 
     ordering = ['-request_made'] 

我想列出所有未订阅的退订客户和仅为用户的联系人。

queryset = Unsubscribe.objects.filter() 

以上给了我所有退订的客户和联系人的任何用户通常我会做解决这个....

queryset = Unsubscribe.objects.filter(user=request.user) 

然而,退订对象没有用户,而且均与客户联系人呢。

那么如何过滤通用关系呢?

回答

1

你可以试试这个

Unsubscribe.objects.filter(content_type__name='user', user=request.user) 

content_type__name='user'指定用户或任何你有相关的IT模型类的名称。

或者,这也

Unsubscribe.objects.filter(content_type__name='user', object_id=request.user.id) 
+0

我累了,这也查询集= Unsubscribe.objects.filter(content_object__contact_owner = self.request.user),但它指出content_object不存在,当它确实。 – GrantU

+0

我不认为'content_obect __...'是有效的字段查找,请尝试使用我指定的。 – Rohan

2

我假设你的模式是这样的:

class Contact(models.Model): 
    ... 
    user = models.ForeignKey(User) 

可以使用获得所有与当前用户联系人:

contact_ids = [each.id for each in request.user.contact_set.all()] 

你可以获取该用户的所有未订阅联系人:

unsubscribed_contacts = Unsubscribe.objects.filter(content_type__name='contact', object_id__in=contact_ids) 
1

请记住,通用外键只是两个字段,一个是指向ContentType模型的ForeignKey,另一个是您指向的任何模型的主键。所以,为了更通用的,你可以做这样的事情:

content_type = ContentType.objects.get_for_model(User) 
Unsubscribe.objects.filter(content_type=content_type, object_id=user.id)