Django Admin 中多表继承的 ValueError
我创建了两个继承模型 Entry 的新类:
class Entry(models.Model):
LANGUAGE_CHOICES = settings.LANGUAGES
language = models.CharField(max_length=2, verbose_name=_('Comment language'), choices=LANGUAGE_CHOICES)
user = models.ForeignKey(User)
country = models.ForeignKey(Country, null=True, blank=True)
created = models.DateTimeField(auto_now=True)
class Comment(Entry):
comment = models.CharField(max_length=2000, blank=True, verbose_name=_('Comment in English'))
class Discount(Entry):
discount = models.CharField(max_length=2000, blank=True, verbose_name=_('Comment in English'))
coupon = models.CharField(max_length=2000, blank=True, verbose_name=_('Coupon code if needed'))
通过 admin.site.register 将这些新模型添加到管理后,在尝试通过管理创建评论或折扣时,我收到 ValueError 。添加条目效果很好。
错误消息:
/admin/reviews/discount/add/ 处的 ValueError 无法分配“''”:“Discount.discount”必须是“Discount”实例。 请求方式:GET 请求网址: http://127.0.0.1:8000/admin/reviews/discount/添加/ 异常类型:值错误 异常值:
无法分配“''”:“Discount.discount”必须是“Discount”实例。 异常位置:set中的/Library/Python/2.6/site-packages/django/db/models/fields/lated.py,第211行 Python 可执行文件:/usr/bin/python Python版本:2.6.1
I created two new classes which inherit model Entry:
class Entry(models.Model):
LANGUAGE_CHOICES = settings.LANGUAGES
language = models.CharField(max_length=2, verbose_name=_('Comment language'), choices=LANGUAGE_CHOICES)
user = models.ForeignKey(User)
country = models.ForeignKey(Country, null=True, blank=True)
created = models.DateTimeField(auto_now=True)
class Comment(Entry):
comment = models.CharField(max_length=2000, blank=True, verbose_name=_('Comment in English'))
class Discount(Entry):
discount = models.CharField(max_length=2000, blank=True, verbose_name=_('Comment in English'))
coupon = models.CharField(max_length=2000, blank=True, verbose_name=_('Coupon code if needed'))
After adding these new models to admin via admin.site.register I'm getting ValueError when trying to create a comment or a discount via admin. Adding entries works fine.
Error msg:
ValueError at /admin/reviews/discount/add/
Cannot assign "''": "Discount.discount" must be a "Discount" instance.
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/reviews/discount/add/
Exception Type: ValueError
Exception Value:
Cannot assign "''": "Discount.discount" must be a "Discount" instance.
Exception Location: /Library/Python/2.6/site-packages/django/db/models/fields/related.py in set, line 211
Python Executable: /usr/bin/python
Python Version: 2.6.1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
出现此错误的原因是因为我使用了与模型名称已使用的相同的列名称。 Karen T. 在 Django 邮件列表中贡献了以下答案:
The reason for this error appeared was because I used same column name that was already used with model name. Karen T. contributed the following answer in Django mailing list:
Hunch 说你可以将 Entry 类声明为抽象类,除非你也需要一个 Entry 作为实际对象
Hunch says you could do with declaring your Entry class as an abstract one unless you need an Entry as an actual object, too