Limit Maximum Choices of ManyToManyField

后端 未结 3 1308
清酒与你
清酒与你 2021-02-20 16:51

I\'m trying to limit the maximum amount of choices a model record can have in a ManyToManyField.

In this example there is a BlogSite that can be related to Regions. In t

3条回答
  •  借酒劲吻你
    2021-02-20 17:45

    The best that I can think of is to have a pre-save signal for BlogSite and check whether this instance of BlogSite has already had 3 regions.

    @receiver(pre_save, sender=BlogSite)
    def check_regions_limit(sender, instance, **kwargs):
        if instance.regions.count() == 3: 
             raise_some_exception("Can't add more than 3 regions to a BlogSite")
    

提交回复
热议问题