如何在 Django 中使多对多字段成为可选字段? [英] How do I make many-to-many field optional in Django?

查看:27
本文介绍了如何在 Django 中使多对多字段成为可选字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您具有多对多关系(related_name,而不是 through)并且您尝试使用管理界面时,您需要输入其中一个即使创建第一个条目不必存在关系.

When you have a many-to-many relationship (related_name, not through) and you are trying to use the admin interface you are required to enter one of the relationships even though it does not have to exist for you to create the first entry.

我正在创建一个作为活动组织者的应用.想象一下,我们有 EventGroup 模型,绑定了多对多关系.

I'm creating an app that is an event organizer. Imagine we had Event and Group models, bound with many-to-many relationship.

Django related_name 使用另外两个表的索引创建另一个表.
但我认为没有理由必须填充这个额外的表格.

Django related_name creates another table with the indices of the two other tables.
But I see no reason why this extra table has to be populated.

如果我通过 phpMyAdmin 使用数据库,我可以创建一个 Group 而无需注册 Event,因为两者之间的连接只通过一个单独的表,并且在给定级别没有数据库值强制执行.

If I work with the database through phpMyAdmin I can create a Group without registering an Event, since the connection between the two is only through a separate table, and there is no database value enforcement at given level.

如何让这个管理界面实现呢?
如何在 Django 中将多对多字段设为可选?

How do I make the admin interface this realize it?
How do I make the many-to-many field optional in Django?

推荐答案

如果您希望能够指定 ManyToMany 关系而不需要它,只需使用 blank=True:

If you want to be able to specify ManyToMany relation without making it required just use blank=True:

class Group(models.Model):
    ...
    events = models.ManyToManyField(Event, blank=True)

这篇关于如何在 Django 中使多对多字段成为可选字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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