Django - 模型中的ManyToManyField,将其设置为null?

发布于 2024-09-27 06:13:39 字数 735 浏览 0 评论 0原文

我有一个 django 模型 (A),它有一个 ManyToManyField (类型)到另一个模型 (B)。从概念上讲,A 中的字段是“可选择将此对象限制为这些值”。我已在 ManyToManyField 上设置 blank=nullnull=True。我已经从这个模型创建了一个对象,并将类型设置为一些值。一切都很好。

我想将其设置为“null”,即禁用它。但在 django shell 中,我收到以下错误:

>>> o.types.all()
[<Type: foo>, <Type: bar>]
>>> o.types = None
File "<console>", line 1, in <module>
File ".../virtualenv/lib/python2.6/site-packages/django/db/models/fields/related.py", line 627, in __set__
manager.add(*value)
TypeError: add() argument after * must be a sequence, not NoneType

我可以成功将其设置为 [] (空列表),但我想将其设置为 None,因为我想使用 None 作为一个信号/标志。这在 Django 模型中可能吗?

我正在使用 Django 1.1

I have a django model (A) which has a ManyToManyField (types) to another model (B). Conceptually the field in A is an 'optionally limit this object to these values'. I have set blank=null and null=True on the ManyToManyField. I have created an object from this model, and set types to some values. All is good.

I want to set it to 'null', i.e. disable it. But in the django shell, I get the following errors:

>>> o.types.all()
[<Type: foo>, <Type: bar>]
>>> o.types = None
File "<console>", line 1, in <module>
File ".../virtualenv/lib/python2.6/site-packages/django/db/models/fields/related.py", line 627, in __set__
manager.add(*value)
TypeError: add() argument after * must be a sequence, not NoneType

I can successfully set it to [] (the empty list), but I would like to set it to None, since I want to use None as a signal/flag. Is this possible in Django models?

I'm using Django 1.1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

自此以后,行同陌路 2024-10-04 06:13:39

我认为不可能将其设置为 None - 想想 M2M 在 SQL 层上是如何实现的(它是一个中间表,你可以将“None”写入哪里?)。

如果您需要一个单独的标志,为什么不引入另一个列呢?

I don't think it is possible to set it to None - think about how M2M is implemented on the SQL layer (it is an intermidiate table, where can you write your "None" to?).

If you need a separate flag, why not introduce another column?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文