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?