限制ManyToManyField的最大选择 [英] Limit Maximum Choices of ManyToManyField
问题描述
我试图限制模型记录在ManyToManyField中可以选择的最大数量。
I'm trying to limit the maximum amount of choices a model record can have in a ManyToManyField.
在此示例中,有一个BlogSite可以与地区。在此示例中,我想将BlogSite限制为只能具有3个区域。
In this example there is a BlogSite that can be related to Regions. In this example I want to limit the BlogSite to only be able to have 3 regions.
这似乎是之前或之后几次被要求/回答的问题。闲逛了几个小时,我无法找到任何东西。对于这个项目,我正在使用Django 1.3。
This seems like something that would have been asked/answered before, but after a couple hours of poking around I haven't been able to find anything close. For this project, I'm using Django 1.3.
#models.py
class BlogSite(models.Model):
blog_owner = models.ForeignKey(User)
site_name = models.CharField(max_length=300)
region = models.ManyToManyField('Region', blank=True, null=True)
....
class Region(models.Model):
value = models.CharField(max_length=50)
display_value = models.CharField(max_length=60)
....
有什么想法吗?
推荐答案
您可以在 BlogSite
上覆盖 clean
方法
from django.core.exceptions import ValidationError
class BlogSite(models.Model):
blog_owner = models.ForeignKey(User)
site_name = models.CharField(max_length=300)
regions = models.ManyToManyField('Region', blank=True, null=True)
def clean(self, *args, **kwargs):
if self.regions.count() > 3:
raise ValidationError("You can't assign more than three regions")
super(BlogSite, self).clean(*args, **kwargs)
#This will not work cause m2m fields are saved after the model is saved
如果使用Django的ModelForm,则会出现此错误在表单的non_field_errors中。
And if you use django's ModelForm then this error will appear in form's non_field_errors.
编辑:
M2m字段在保存模型后保存,因此上面的代码将无法正常工作,可以使用 m2m_changed
信号的正确方法:
M2m fields are saved after the model is saved, so the code above will not work, the correct way you can use m2m_changed
signal:
from django.db.models.signals import m2m_changed
from django.core.exceptions import ValidationError
def regions_changed(sender, **kwargs):
if kwargs['instance'].regions.count() > 3:
raise ValidationError("You can't assign more than three regions")
m2m_changed.connect(regions_changed, sender=BlogSite.regions.through)
尝试一下对我有用。
这篇关于限制ManyToManyField的最大选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!