Limit another app's GenericForeignKey choices

1.1k Views Asked by At

I am writing a reusable Carousel app. It needs to refer to a model in the main project, so I have used a generic foreign key. I have something like this in the reusable app:

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class MyCarousel(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_group = generic.GenericForeignKey('content_type', 'object_id')
    ...

Now I would like the project to be able to limit the content_type's type. If I was doing this in the above class declaration I could rewrite the content_type line as follows:

    content_type = models.ForeignKey(ContentType, limit_choices_to=models.Q(app_label = 'myapp', model = 'mymodel'))

But the reusable app doesn't know which model it will be used with, so I want to limit the choices later, in the project.

Can this be done? E.g. like this pseudo-code:

import my_carousel.models
my_carousel.models.MyCarousel.content_type.limit_choices_to = models.Q(app_label = 'myapp', model = 'mymodel')

Actually, my objective is to let the admin choose only from a specific model. So a solution that implements it there would be even better.

Thanks!

0

There are 0 best solutions below