我如何在 Django 中创建一个没有 manytomanyfield 的多值字段?

How i can create a muti value filed without manytomany field in django?

我有一个模型:

class People(models.Model):
   family = models.CharField(null=True)
   phone_numbers = ?

我如何为某些 phone 号码实施 phone_numbers。我认为 ManyToManyField 不是这样做的好主意。

这方面的最佳做法是什么?

admin.py

class PhonesInline(admin.TabularInline):
    model = models.Phones

class PeopleAdmin(admin.ModelAdmin):
    inlines = [
        PhonesInline,
    ]
admin.site.register(models.People, PeopleAdmin)

您可以做的是创建一个 Phone 模型并使用 ForeignKeyPhonePeople 之间创建 Many-to-one 关系。有了这个,您可以将各种 phone 号码关联到一个人。

class People(models.Model):
    family = models.CharField(null=True)


class Phone(models.Model):
    number = models.CharField(max_length=15, unique=True)
    person = models.ForeignKey(People, on_delete=models.CASCADE)

现在,例如,如果您在名为 people 的变量中有一个 People 实例,您可以使用 values_list 访问其相关的 phone 数字:

people.phone_set.values_list('number', flat=True)

请注意您的型号,不建议使用 null=TrueCharField/TextFieldofficial Django documentation 声明如下:

Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.

你也可以看看 this question,它解决了我的最后一点。

此外,我不知道您要将哪种逻辑应用于您的项目,但我认为组织模型及其关系的更好方法是创建一个 Family class 来处理与这样的家庭:

class Family(models.Model):
    name = models.CharField(max_length=100)


class People(models.Model):
    family = models.ForeignKey(Family, blank=True, null=True)


class Phone(models.Model):
    number = models.CharField(max_length=15, unique=True)
    person = models.ForeignKey(People, on_delete=models.CASCADE)

有了这个额外的模型,您将能够在 PeopleFamily 之间创建另一个 Many-to-one 关系。根据您的需要,您应该在创建字段时调整参数,我提供的参数只是一个示例。