Djang的模型继承

2024-09-28 20:49:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一节课:

class ControlVocabulary(models.Model):
    definition = models.TextField()
    term = models.CharField(primary_key=True, max_length=255)

    class Meta:
        abstract = True

为什么我不能在子类中使用“definition”?有没有办法让我这么做?你知道吗

class ActionType(ControlVocabulary):
    definition = ControlVocabulary.definition # <-- Error
    class Meta:
        #...

更新: 看起来这在Django是不允许的,但是我仍然在寻找解决这个问题的方法。In Django - Model Inheritance - Does it allow you to override a parent model's attribute?

我的视图类:

class VocabulariesView(ListView):
queryset = []
template_name = 'cvinterface/index.html'

def get_context_data(self, **kwargs):
    context = super(VocabulariesView, self).get_context_data(**kwargs)
    context['vocabulary_views'] = [{'name': vocabularies[vocabulary_name]['name'], 'definition': vocabularies[vocabulary_name]['definition'], 'url': reverse(vocabulary_name)}
                                   for vocabulary_name in vocabularies]

    return context

词汇词典的一部分:

vocabularies = {
# optional keys:
# list_view, detail_view, list_template, detail_template

'actiontype': {
    'name': ActionType._meta.verbose_name,
    'definition': ActionType._meta.definition,
    'model': ActionType,
    'detail_template': 'cvinterface/vocabularies/actiontype_detail.html',
},

Tags: djangonametruemodelmodelscontexttemplatemeta
1条回答
网友
1楼 · 发布于 2024-09-28 20:49:18

您不必在ActionType中定义definition,因为它已经从ControlVocabulary继承了

您可以按如下方式进行检查:

x = ActionType.objects.all()
x[0].__dict__

另一种检查方法是查看数据库中模型的字段

编辑:

尝试复制错误:

型号:

class ControlVocabulary(models.Model):
    definition = models.TextField()
    term = models.CharField(primary_key=True, max_length=255)
    class Meta:
        abstract = True
class ActionType(ControlVocabulary):
    #definition = ControlVocabulary.definition # <  Error
    class Meta:
        verbose_name='Action'

在贝壳里:

Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from testapp.models import *
>>> x = ActionType.objects.all()
>>> x
[]
>>> y = ActionType(definition='my definition')
>>> y.save()
>>> ActionType.objects.all()
[<ActionType: ActionType object>]

相关问题 更多 >