Django - How to declare IntegerChoice & IntegerField for the whole django project (globally)

Viewed 224

I defined following class:

class LocationInterestRegion(models.Model):

    class LocationInterestRegionTypes(models.IntegerChoices):
        CITY = 0 , _('city level')
        COUNTY = 1 , _('province level')
        STATE = 2 , _('regio/state level')
        COUNTRY = 3 , _('country level')
        INTERNATIONAL = 4 , _('international level')

        __empty__ = _('Select the region from where to find candidates.')

    location_interest_region = models.IntegerField(choices=LocationInterestRegionTypes.choices, null=True)

And then tried to use this in another model as a ForeignKey


class Job(models.Model):
    location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=True, null=True)
    location_interest_region = models.ForeignKey(LocationInterestRegion, on_delete=models.CASCADE,blank=True, null=True)

Now I cannot access the options in my form.

class JobCreateForm(forms.ModelForm):

    class Meta:
        model = my_model
        fields = [
                'location',
                'location_interest_region', 
                ]

       

I could solve the issue by not using the foreign key and intergrating the first model in the second one.

But if I want to use these "choices" in several other models. I need to redefine them in every model.

Is there a way to define these choices globally ?

1 Answers

I already found the answer. (very obvious)

In my second model (class Job(models.Model)) I removed this line:

location_interest_region = models.ForeignKey(LocationInterestRegion, on_delete=models.CASCADE,blank=True, null=True)

Then I imported the 'LocationInterestRegion' and added following line:

location_interest_region = models.IntegerField(choices=LocationInterestRegion.LocationInterestRegionTypes.choices, null=True)

In my folder 'utils' (same level as app names) I created a file choices.py. And there I added the choices.

from django.db import models
from django.utils.translation import ugettext_lazy as _

class LocationInterestRegionTypes(models.IntegerChoices):
    CITY = 0 , _('city level')
    COUNTY = 1 , _('province level')
    STATE = 2 , _('regio/state level')
    COUNTRY = 3 , _('country level')
    INTERNATIONAL = 4 , _('international level')

    __empty__ = _('Select the region from where to find candidates.')

Now I can import this in any Model by using from utils.choices import LocationInterestRegionTypes.

and use location_interest_region = models.IntegerField(choices=LocationInterestRegionTypes.choices, null=True)

Related