How to filter generic foreign keys?

1000 views Asked by At

I have these models:

class EventEntry(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    start_date =  models.DateTimeField(...)
    end_date = models.DateTimeField(...)
    field = models.CharField(max_length=64)

class ObjectPerm(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    public = models.BooleanField(...)
    users = models.ManyToManyField(User...)
    groups = models.ManyToManyField(Group...)

class Meeting(models.Model):
    scheduled_time = generic.GenericRelation(EventEntry)
    room = models.CharField(max_length=8)
    permissions = GenericRelation(ObjectPerm)

class Milestone(models.Model):
    due_date = generic.GenericRelation(EventEntry)
    title = models.CharField(max_length=128)
    permissions = GenericRelation(ObjectPerm)

The EventEntry class is used to attach scheduling information to any object, such as Meeting and Milestone.

The ObjectPerm class provides object level permissions to any model that needs protection.

When I create an instance of Meeting, I assign an EventEntry instance for the schedule information. I also assign ObjectPerm instances to specify which users can access the meeting object.

There are more models like Meeting and Milestone.

Now, what I want to do is retrieve EventEntry instances, but only those for related objects the user has permission to access, based on the ObjectPerm model.

For example all EventEntry instances where public == True or the user is in the EventEntry field "users". This way I can pull out all the events to display in a calendar but I don't need to filter the meetings, milestones etc. Except I can't work out how to write this filter in Python using Django's ORM.

1

There are 1 answers

2
ZeroSoul13 On

Have you taken a look at the docs? the information seems pretty helpful to me. This might be useful as the way i see it with my (little) experience this could potentially require a couple of calls to get the job done. Hope it works

https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations