Reputation: 7400
i have a Django model class as follows:
class IPGroup(BaseModel):
"""
Stores IP Groups
"""
name = models.CharField(max_length=50, unique=True)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
_ips = models.ManyToManyField(IP, through='connectivity_service.IPGroupToIP', null=True)
_cidrs = models.ManyToManyField(CIDR, through='connectivity_service.IPGroupToCIDR', null=True)
_ip_groups = models.ManyToManyField('self', through='connectivity_service.IPGroupToIPGroup', null=True,
symmetrical=False)
def __unicode__(self):
return f'{self.name}'
class Meta:
app_label = 'connectivity_service'
As is evident, the fields _ips
,_cidrs
and ip_groups
can be null in the database.However, I want to prevent all 3 of them being null together when the model is saved. In other words, when the model is saved, atleast one of those 3 fields should not be null.
Upvotes: 0
Views: 84
Reputation: 599470
Firstly, null
doesn't have any meaning with a many-to-many field, as that's not actually a column in the database but an entry in a completely separate table.
In any case, if you want to require that at least one of those fields is non-empty, you need to do it at validation time; it's not something you can just specify in the model definition.
But note also, for the same reason as above, you can't do this before creating the model initially; many-to-many fields can't have a value before creation, because they need the ID to create the item in the through table.
Upvotes: 1