Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a way of telling django that a model having a contenttypes GenericForeignKey can only point to models from a predefined list? For example, I have 4 models: A, B, C, D and a model X that holds a GenericForeignKey. Can I tell X that only A & B are allowed for the GenericForeignKey?

like image 871
Geo Avatar asked Jun 13 '11 20:06

Geo


People also ask

Should I use Django models?

Use Django models when you need to dynamically load information in your project. For example, if you create a blog don't hard code every piece of article content. Create an article model with the article title, URL slug, and content as the model fields.

What are models in Django used for?

Django web applications access and manage data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc.


1 Answers

For example, your apps are app and app2 and there are A, B models in app and there are C, D models in app2. 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 on ForeignKey.

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

plus: I think you write wrong app_label. This can help you.

from django.contrib.contenttypes.models import ContentType for c in ContentType.objects.all():     print(c.app_label, c.model) 
like image 100
mumino Avatar answered Sep 25 '22 00:09

mumino