在django中限制ManyToManyField的关系数。

问题描述 投票:7回答:2

我在我的代码中使用ManyToMany的关系,我有展厅和它们的类别。现在一个展厅最多可以分为三个类别,我必须在保存时验证它。下面是我的代码。

##models.py
class Showrooms(models.Model):
    name = models.CharField(max_length = 100)
    contact_person = models.CharField(max_length = 100)
    offer = models.TextField()
    categories = models.ManyToManyField(Categories, null=True, blank=True,    related_name='categories')


    class Meta:
        db_table = 'showrooms'
        verbose_name_plural = "showrooms"


class Categories(models.Model):
    category = models.CharField(max_length = 100)
    image = models.ImageField(upload_to = showroom_upload_path, null=True, blank=True)
    slug = models.SlugField(blank=True)

    class Meta:
        db_table = 'showroom_categories'
        verbose_name_plural = "categories"

    def __str__(self):
        return self.category

一切都在正常工作,除了我无法对每个展厅的类别数量进行验证。我不使用它的意见,但只是想在管理。

请帮助

谢谢你

编辑

好吧......我已经解决了我的问题。我在forms.py中创建了一个表单

class ShowroomsForm(forms.ModelForm):
    class Meta:
        model = Showrooms

    def clean(self):
        categories = self.cleaned_data.get('categories')
        if categories and categories.count() > 3:
            raise ValidationError('Maximum three categories are allowed.')

        return self.cleaned_data

并将其添加到admin.py中,如下所示。

class ShowroomsAdmin(admin.ModelAdmin):
    form = ShowroomsForm


admin.site.register(Showrooms, ShowroomsAdmin)
django django-models django-orm
2个回答
2
投票

你可以在你的模型上定义一个clean()方法,当一个展厅被分配到3个以上的类别时,就会产生一个验证错误。

https:/docs.djangoproject.comen1.5refmodelsinstances#django.db.models.Model.clean。

© www.soinside.com 2019 - 2024. All rights reserved.