Django模型继承,覆盖字段 [英] Django model inheritance, overriding fields

查看:940
本文介绍了Django模型继承,覆盖字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读使用Django的Python Web Development一书,我在书中找到了这个例子:

I am reading the book Python Web Development with Django and I found this example in the book:

 class Book(models.Model):
            title = models.CharField(max_length=100)
            genre = models.CharField(max_length=100)
            num_pages = models.IntegerField()
            authors = models.ManyToManyField(Author)

            def __unicode__(self):
                return self.title

    class SmithBook(Book):
        authors = models.ManyToManyField(Author, limit_choices_to={'name__endswith': 'Smith'})

好像不是工作:


FieldError:类'SmithBook'中的本地字段'authors'与基类'Book'中类似名称的字段发生冲突

FieldError: Local field 'authors' in class 'SmithBook' clashes with field of similar name from base class 'Book'

我使用的是Django 1.5.3,本书适用于Django 1.0。

I am using Django 1.5.3 and the book is for Django 1.0.

为什么在inh时无法覆盖字段Django的优点?是否有可能在Django 1.0中,或者这本书中有错误?

Why it is not possible to override fields when inherit in Django? Was it possible in Django 1.0, or it is an error in the book?

推荐答案

不要认为这是允许的django,甚至不是1.0。

Don't think this has been allowed in django, not even 1.0.

来自字段名称隐藏是不允许的 - django 1.0


在普通的Python类继承中,允许子
类覆盖父类的任何属性。在Django中,这个
不允许属于Field实例的属性(至少目前不是
)。如果基类有一个名为author的字段,那么
不能在
继承自该基类的任何类中创建另一个名为author的模型字段。

In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this is not permitted for attributes that are Field instances (at least, not at the moment). If a base class has a field called author, you cannot create another model field called author in any class that inherits from that base class.

这仍然适用于最新版本的django。

This still holds for the latest version of django.

这篇关于Django模型继承,覆盖字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆