Django在选择列表更改中创建无意义的迁移 [英] Django creates pointless migrations on choices list change

查看:331
本文介绍了Django在选择列表更改中创建无意义的迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用可调用的方式创建一个具有选择字段的模型,以便Django在选择列表更改时不创建迁移,如这个这个问题。

I'm trying to create a model with a choices field using a callable, so that Django doesn't create migrations when a choices list changes, as stated in this question here.

class Quote(models.Model):
    severity = models.IntegerField(choices=get_severity_choices)
    ...

class get_severity_choices(object):
    def __iter__(self):
        for item in SEVERITY_CHOICES:
            yield item

其中

SEVERITY_CHOICES = (
    (1, 'Low'),
    (2, 'Medium'),
    (3, 'High'),
)

但是,我收到一条错误消息:

However, I'm getting an error message:

quoting.Quote.severity: (fields.E004) 'choices' must be an iterable (e.g., a list or tuple).


推荐答案

我想你在混合 c c c c c c c 领域。在模型中,选项必须是可交互的 - 您不能通过callable:

I think you're mixing up the choices argument on a Model field, and that on a forms.ChoiceField field. In a model, choices must be an interable - you cannot pass a callable:


选择:一个包含
的两个项(例如[(A,B),(A,B)...])的迭代的迭代(例如,列表或元组))用作
此字段。

choices: An iterable (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) ...]) to use as choices for this field.

您的 get_severity_choices 类不是被认为是一个迭代,因为Django希望它可以将 集合可以 ,而不仅仅是公开一个 __ iter __ 方法。

Your get_severity_choices class isn't being recognised as an iterable because Django expects it to subclass collections.Iterable rather than just expose an __iter__ method.

可以通过 a可调用 FormField


财ces :要用作此字段的选择的二元组的迭代(例如,列表或元组),或可返回此类迭代的可调用。

choices: Either an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field, or a callable that returns such an iterable.

对于模型字段,您必须事先指定您的选择。还可以从文档中获取:

For a Model field however you must specify your choices beforehand. Also from the docs:


请注意,选择可以是任何可迭代对象必须有一个列表
或元组。这使您可以动态构建选择。但是,如果你发现
自己黑客选项是动态的,那么你可能会使用一个具有ForeignKey的正确的数据库表
选项适用于
静态数据,如果有任何变化,则不会发生太大变化。

Note that choices can be any iterable object – not necessarily a list or tuple. This lets you construct choices dynamically. But if you find yourself hacking choices to be dynamic, you’re probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn’t change much, if ever.


$关于为什么Django创建似乎无用的迁移,在此门票中有一些讨论


这是设计。有几个原因,其中尤其重要的是,历史上的点数据移动需要有一个完整的
准确的模型表示,包括所有的选项,而不是
只是影响数据库的那些。

This is by design. There are several reasons, not least of which ... that datamigrations at points in history need to have a full accurate representation of the models, including all their options, not just those which affect the database.

这篇关于Django在选择列表更改中创建无意义的迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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