如何在 table 模型中使用先前填充夹具的选项

How to use choices in a model from a table previously populated with a fixture

我有以下型号:

class Countries(models.Model):
    region = models.CharField(max_length=250, null=False, blank=False)
    country = models.CharField(max_length=250, null=False, blank=False, unique=True)

我通过 python manage.py loaddata db.json(JSON 夹具)填充模型

填充模型后,我想将这些地区和国家用作另一个模型字段'options'

class Project(models.Model):
    project_code = models.CharField(max_length=250, null=False, blank=False)
    status = models.CharField(#when creating a new project: default - active
        max_length=250, 
        null=True, 
        blank=True, 
        default=PROJECT_STATUS_DEFAULT,
        choices=PROJECT_STATUS,
    )
    region = models.CharField(
        max_length=250, 
        null=False, 
        blank=False, 
        default=, #I would like to use here the options available in the Countries model
        choices=, #I would like to use here the options available in the Countries model
    )
    country = models.CharField(
        max_length=250, 
        null=False, 
        blank=False,
        default=, #I would like to use here the options available in the Countries model
        choices=  #I would like to use here the options available in the Countries model
    )

我做了一些研究,我很清楚如何使用 constants.py 文件中的选项,但我没有找到很好的解释 关于如何将它与以前填充的模型一起使用。

由于 Countries 已经包含您的数据,请使用从 ProjectCountriesmodels.ForeignKey,这样您就可以 select 现有条目。

class Countries(models.Model):
    region = models.CharField(max_length=250, null=False, blank=False)
    country = models.CharField(max_length=250, null=False, blank=False, unique=True)

    def __str__(self):
        return f'{self.region} - {self.country}'


class Project(models.Model):
    project_code = models.CharField(max_length=250, null=False, blank=False)
    status = models.CharField(#when creating a new project: default - active
        max_length=250, 
        null=True, 
        blank=True, 
        default=PROJECT_STATUS_DEFAULT,
        choices=PROJECT_STATUS,
    )
    country = models.ForeignKey(Countries, on_delete=models.PROTECT)

Countries__str__ 方法默认用作 select 表单字段下拉列表的标签