Search code examples
djangodjango-generic-relations

Django filter on generic relationship (unique constraint exception)


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

class ReportedContent(models.Model):

    reporter = models.ForeignKey(User, on_delete=models.CASCADE)

    # Generic relation for posts and replies
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()

    class Meta:
        unique_together = ('reporter', 'object_id', 'content_type')

I would like to check if the content_object is already exists before I get a duplicate key value violates unique constraint exception.

Django documentation mentioned that:

# This will fail
>>> ReportedContent.objects.filter(content_object=content)
# This will also fail
>>> ReportedContent.objects.get(content_object=content)

So how can I filter on generic relation? or how can I deal with this exception specifically?


Solution

  • you can filter by object_id and content_type. just make sure you do it right, get content_type this way:

    from django.contrib.contenttypes.models import ContentType
    # ...
    
    content_type = ContentType.objects.get(app_label='name_of_your_app', model='model_name')
    

    for handling the exception :

    if ReportedContent.objects.filter(object_id=content.id,content_type=content_type):
        raise Exception('your exception message')