Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter on generic relationship

Tags:

django

I have a model below which points to a generic relationship. This can either be a contact object or a customer object.

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']

I would like to list out all unsubscribed both unsubscribe customers and contacts only for the user.

 queryset = Unsubscribe.objects.filter()

Above gives me all unsubscribe customers and contacts for any users normally I would solve this by doing....

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

However, Unsubscribe object does not have a user, but both customers and contacts do.

So how can I filter on the generic relationship?

like image 221
GrantU Avatar asked Jul 08 '13 12:07

GrantU


People also ask

Can you filter by property Django?

Django-property-filter is an extension to django-filter and provides functionality to filter querysets by class properties. It does so by providing sub-classes for Filters and Filtersets to keep existing django-filter functionality. For more details and examples check the documentation.

What is Genericrelation in Django?

Basically it's a built in app that keeps track of models from the installed apps of your Django application. And one of the use cases of the ContentTypes is to create generic relationships between models.


1 Answers

You could try this

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

For content_type__name='user' specify name of your model class for user or whatever you have associated it with.

Or this also

Unsubscribe.objects.filter(content_type__name='user', object_id=request.user.id)
like image 179
Rohan Avatar answered Nov 10 '22 00:11

Rohan