Can I limit the choices in a ContentType field in admin?

2,621 views
Skip to first unread message

Adam Stein

unread,
Mar 23, 2009, 3:26:22 PM3/23/09
to django...@googlegroups.com
Trying to create a generic FK using ContentType. In admin, the menu
lists all the models. Since I only ever need to select 1 of 2 different
models, anyway to limit the choice?

Setting the choices attribute as Django complains

must be a "ContentType" instance

ContentType.objects.get() returns an instance of a particular model, not
ContentType (as one would expect), so I'm not sure how to create an
instance with the particulars I need to point to something specific in
the choices list. Here's what I have:

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

class GenericFKExample(models.Model):
CHOICES = (
(ContentType.objects.get(model="model1"), "Model 1"),
(ContentType.objects.get(model="model2"), "Model 2"),
)

content_type = models.ForeignKey(ContentType,
choices = CHOICES,
null = True,
)

object_id = models.PositiveIntegerField(
null = True,
)

content_object = generic.GenericForeignKey(
"content_type", "object_id"
)

Obviously, if I don't use choices, it works but then I have a very long
list of model choices.

--
Adam Stein @ Xerox Corporation Email: ad...@eng.mc.xerox.com

Disclaimer: Any/All views expressed
here have been proven to be my own. [http://www.csh.rit.edu/~adam/]

Lee

unread,
Apr 1, 2009, 11:48:30 AM4/1/09
to Django users
You're close...

change your method in CHOICES to get_for_model( _model_ )

So it should be
CHOICES = (
(ContentType.objects.get_for_model(My_Model), "Model 1"),
(ContentType.objects.get_for_model(My_Other_Model), "Model
2"),
)

Obviously, make sure you import your model before you try to use it.
> Adam Stein @ Xerox Corporation       Email: a...@eng.mc.xerox.com

Adam Stein

unread,
Apr 1, 2009, 1:30:49 PM4/1/09
to django...@googlegroups.com
Thanks for the info. I also ran across 'limit_choices_to' which also
works.
Adam Stein @ Xerox Corporation Email: ad...@eng.mc.xerox.com

Lee

unread,
Apr 1, 2009, 1:34:23 PM4/1/09
to Django users
Actually I tried to do as I suggested and I couldn't get it to
work... I ended up using the following:

from MyProject.MyApp.models import MyModel

CONTENT_TYPE_CHOICES = (ContentType.objects.get_for_model
(MyModel).id,)

class My_Other_Model(models.Model):
content_type = models.ForeignKey(ContentType, limit_choices_to=
{'id__in': CONTENT_TYPE_CHOICES})

Adam Stein

unread,
Apr 1, 2009, 1:43:26 PM4/1/09
to django...@googlegroups.com
I wound up doing it that way as well except I used the model name rather
than the ID:

data_type = models.ForeignKey(ContentType,
limit_choices_to = {"model__in": ("model1", "model2")},
)
Adam Stein @ Xerox Corporation Email: ad...@eng.mc.xerox.com
Reply all
Reply to author
Forward
0 new messages