Search code examples
djangodjango-modelsdjango-admindjango-contenttypes

Customize Django ContentType


I have a model like this:

class BlockedItem(models.Model):
    name = models.CharField(max_length=244)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    def __unicode__(self):
        return self.name
  • In django admin, content_type fetch all models. Could I give only wanted models in content_type ?

  • In object_id, is there any way to select from a list instead of enter object_id ?


Solution

  • If you want only some models in content_type you can use

    limit_choices = models.Q(app_label = 'myapp', model = 'MyModel') | models.Q(app_label = 'myotherapp', model = 'MyModelOtherModel') )
    content_type = models.ForeignKey(ContentType, limit_choices_to = limit_choices )