【问题标题】:Customize Django ContentType自定义 Django ContentType
【发布时间】:2014-08-01 10:53:21
【问题描述】:

我有一个这样的模型:

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
  • 在 django admin 中,content_type 获取所有模型。我可以在content_type 中只提供想要的模型吗?

  • object_id中,有没有办法从列表中选择而不是输入object_id

【问题讨论】:

    标签: django django-models django-admin django-contenttypes


    【解决方案1】:

    如果你只想要 content_type 中的一些模型,你可以使用

    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 )
    

    【讨论】:

    • 非常感谢,但是“object_id”呢?我想我必须使用 javascript 来收集所选对象的项目。我说的对吗?
    • 我认为一个解决方案可以(不确定它是否更好)覆盖您的对象Django Doc 的管理表单,以便预先填充具有所需值的ChoiceFields .当您更改 content_type 时,您将需要一些 javascript 从一个 ChoiceField 切换到另一个
    • 只需检查模型是否以小写字母开头,例如 mymodel 而不是 Mymodel
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 2011-08-01
    • 2015-07-17
    • 2010-12-24
    • 2021-09-01
    • 2014-06-28
    相关资源
    最近更新 更多