I'm have a simple model using a GenericForeignKey object. I would like to limit the allowed content_objects
to a specific, static set of models. Lets say, I would only like it to accept ModelA
and ModelB
from app_a
and app_b
, respectively.
I ran across this question that essentially describes what I'm trying to achieve. I implemented the proposed solution, and I end up with a model that looks something like this:
class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
limit = models.Q(app_label='app_a', model='modela') \
| models.Q(app_label='app_b', model='modelb')
content_type = models.ForeignKey(ContentType, limit_choices_to=limit)
content_object = GenericForeignKey('content_type', 'object_id')
This actually appears to work correctly when using the /admin/ panel to add the object, the content_type
pulls from my available options. However, when I write unit tests, or using the shell, it doesn't seem to enforce this.
For instance, I would expect:
TaggedItem.objects.create(content_object=(ModelZ()))
To raise an exception. However, it doesn't. Is there any django-istic way to enforce the content_objects
to be an instance of a model given in the limit_choices_to
?