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

Time:12-16

I have the following model:

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)

I populate the model via python manage.py loaddata db.json (JSON fixture)

After the model is populated, I would like to use those regions and countries as 'options' for another model field

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
    )

I did some research and it is clear to me how to use choices from a constants.py file, but I have not found a good explanation on how to use it with previous populated models.

CodePudding user response:

Since Countries already contains your data, use a models.ForeignKey from Project to Countries so that you can just select an existing entry.

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)

The __str__ method of Countries is what is used as the label for the select form field dropdown by default

  • Related