Hashim khan
Hashim khan

Reputation: 29

How can I filter, search, and sort fields from a GenericForeignKey that have a GenericRelation in Django?

I have a Django model, AssetAssociation, which contains a GenericForeignKey to various models (Assets, User, Locations). The AssetAssociation model looks like this:

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey


class AssetAssociation(models.Model):
    asset = models.ForeignKey(Assets, on_delete=models.CASCADE, related_name='asset_association')
    target_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    target_id = models.UUIDField()
    target_object = GenericForeignKey('target_type', 'target_id')  # User / Asset / Location
    checkout_date = models.DateField(null=True, blank=True)
    expected_checkin_date = models.DateField(null=True, blank=True)
    checkin_date = models.DateField(null=True, blank=True)
    action_type = models.CharField(max_length=50, choices=ASSOCIATION_ACTION_TYPE_CHOICES)

And here are the related models:

from django.contrib.contenttypes.fields import GenericRelation
class Assets(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True)
    asset_tag = models.CharField(max_length=255)
    asset_associations = GenericRelation('AssetAssociation', content_type_field='target_type', object_id_field='target_id')

class User(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    asset_associations = GenericRelation('AssetAssociation', content_type_field='target_type', object_id_field='target_id')

class Locations(models.Model):
    name = models.CharField(max_length=100)
    asset_associations = GenericRelation('AssetAssociation', content_type_field='target_type', object_id_field='target_id')

How can I effectively filter and sort on these fields using Django's ORM? Specifically, how do I write a filter function that allows filtering on these fields by using the GenericRelation?

Upvotes: 2

Views: 41

Answers (0)

Related Questions