Django - 模型中的ManyToManyField,将其设置为null?
我有一个 django 模型 (A),它有一个 ManyToManyField (类型)到另一个模型 (B)。从概念上讲,A 中的字段是“可选择将此对象限制为这些值”。我已在 ManyToManyField 上设置 blank=null
和 null=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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是
clear()
的用途。http:// docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.lated.RelatedManager.clear
也许您正在寻找
remove()
?http:// docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.lated.RelatedManager.remove
That's what
clear()
is for.http://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.clear
Perhaps you're looking for
remove()
?http://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.remove
我认为不可能将其设置为 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?