How can I restrict Django GenericForeignKey to a list of models?

Is there a way to tell django that a model that has GenericForeignKey content types can only point to models from a predefined list? For example, I have 4 models: A, B, C, D and Model X, which contains a GenericForeignKey. Can I tell X that only A and B are allowed for GenericForeignKey?

+53
django django-models django-admin django-forms django-contenttypes
Jun 13 2018-11-11T00:
source share
1 answer

For example, your applications are application and application2, and in the application there are models A, B, and in application 2 there are models C, D. you want to see only app.A and app.B and app2.C

from django.db import models class TaggedItem(models.Model): tag = models.SlugField() limit = models.Q(app_label = 'app', model = 'a') | models.Q(app_label = 'app', model = 'b') | models.Q(app_label = 'app2', model = 'c') content_type = models.ForeignKey(ContentType, limit_choices_to = limit) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') 

use limit_choices_to for ForeignKey.

check out django docs for details and Q objects, app_label. you need to write a proper app_label and model. This is just a piece of code.

plus: I think you are writing the wrong app_label. It can help you.

 from django.contrib.contenttypes.models import ContentType for c in ContentType.objects.all(): print(c.app_label, c.model) 
+98
Jun 13 2018-11-21T00:
source share



All Articles