在 Django 建模方面需要帮助

Need help on Django Modelling

我正在创建一个 Django 应用程序,这个问题又来打击我了(我已经 运行 进入它,但我以我认为不正确的方式解决了它)。

所以我有这些模型:

def Person(models.Model):
    name = models.CharField(max_length=30)
    status = models.ManyToManyField(Status)

def Status(models.Model):
    name = models.CharField(max_length=30)

任何人最多可以有 3 个状态(或 none)。这应该是一个字符串数组,只包含一些可能的状态。例如快乐,幸运,坚强。

但是这里不可能有选择的 CharField,因为一个人可能同时感到快乐和坚强。

我目前的方法是最好的方法吗?

您需要在 clean 方法中验证每个人的状态计数。

from django.db import models
from django.core.exceptions import ValidationError


class Status(models.Model):
    name = models.CharField(max_length=30)


class Person(models.Model):
    name = models.CharField(max_length=30)
    status = models.ManyToManyField(Status)

    def clean(self):
        # check person status count
        if self.status.all().count() > 3:
            raise ValidationError("Person can not have more than 3 statuses")

更新

因为它是一个 ManyToMany 关系,你永远不会在创建对象的过程中得到这个验证,除非你有一个单独的表单来添加人员的状态

如果您在创建人员的同一表单中有状态字段,则此检查必须在表单中。

class PersonForm(forms.ModelForm):
    class Meta:
        model = Person

    def clean(self):
        statuses = self.cleaned_data.get('status')
        if status.count() > 3:
            raise ValidationError("Person can not have more than 3 statuses")

为什么用这个方法

这种模型设计将允许您有多种不同的查询方式。例如 get people who are happy!count of people who are sad 最后得到具有相似状态的人

只是一个快速补充 - 如果您使用的是 PostgreSQL(这可能是最好的决定),您还可以使用数组字段,您可以为其指定最大大小。

https://docs.djangoproject.com/en/1.8/ref/contrib/postgres/fields/

另一种选择是使用像 Django-taggit

这样的标记库