[英]Django creates pointless migrations on choices list change
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. 我正在尝试使用可调用对象来创建带有选项字段的模型,以便当选项列表更改时,Django不会创建迁移,如本问题所述。
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
where 哪里
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).
I think you're mixing up the choices
argument on a Model
field, and that on a forms.ChoiceField
field. 我认为您在
Model
字段和forms.ChoiceField
字段上混合了choices
参数。 In a model , choices
must be an interable - you cannot pass a callable: 在模型中 ,
choices
必须是可交互的-您不能传递可调用对象:
choices
: An iterable (eg, a list or tuple) consisting itself of iterables of exactly two items (eg [(A, B), (A, B) ...]) to use as choices for this field.choices
:一个可迭代的(例如列表或元组)本身由恰好两个项目(例如[[(A,B),(A,B)...])的可迭代项组成,用作此字段的选择。
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. 您的
get_severity_choices
类未被认为是可迭代的,因为Django希望它get_severity_choices
collections.Iterable
子类。可迭代而不是仅公开__iter__
方法。
You can pass a callable to a FormField
: 您可以将可调用对象传递给
FormField
:
choices
: Either an iterable (eg, a list or tuple) of 2-tuples to use as choices for this field, or a callable that returns such an iterable.choices
:要么是一个2元组的可迭代(例如,列表或元组)用作此字段的选择,要么是返回此类迭代的可调用对象。
For a Model
field however you must specify your choices beforehand. 但是,对于“
Model
字段,您必须事先指定选择。 Also from the docs: 另外从文档:
Note that
choices
can be any iterable object – not necessarily a list or tuple.请注意,
choices
可以是任何可迭代的对象-不一定是列表或元组。 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
是动态的,那么最好使用带有ForeignKey的正确数据库表。choices
is meant for static data that doesn't change much, if ever.choices
是针对不变的静态数据(如果有的话)。
As regards why Django creates the seemingly useless migrations, there is some discussion about that in this ticket : 关于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.
原因有很多,其中不仅仅如此……历史上的各个点的数据迁移都需要对模型进行完全准确的表示,包括它们的所有选项,而不仅仅是影响数据库的那些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.