In my models I'm using the choices
option in some of my fields. But I'm using the same choices in multiple apps in my Django project.
Where should I place my choices and how can I load these choices in all my apps?
Django Field Choices. According to documentation Field Choices are a sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) …]) to use as choices for some field. For example, consider a field semester which can have options as { 1, 2, 3, 4, 5, 6 } only.
Django application consists of project and app, it also generates an automatic base directory for the app, so we can focus on writing code (business logic) rather than creating app directories.
A Django app is a small library representing a discrete part of a larger project. For example, our blog web application might have an app for posts , one for static pages like an About page called pages , and another app called payments to charge logged-in subscribers.
We usually have quite a few project-specific apps per project here, and to try and keep dependencies reasonably clean we usually have two more apps:
"core" in which we put things shared by other apps (any app can depend on "core", "core" doesn't depend on any app),
and "main" in which tie things together ("main" can depend on any app, no app is allowed to depend on "main").
In your case, these shared choices would belong to core.models
.
I like to put all the constants in a file called constants.py inside each app. When we want some kind of global choices shared between the apps, we put them in a "core" app (like @bruno desthuilliers described) and import them when needed.
Example:
constants.py
# -*- coding: utf-8 -*-
STATE_1 = 0
STATE_2 = 1
STATE_3 = 2
STATE_CHOICES = (
(STATE_1, 'STATE 1'),
(STATE_2, 'STATE 2'),
(STATE_3, 'STATE 3')
)
any_app/models.py
from django.db import models
from other.app.models import User
from core.constants import SOME_OTHER_CHOICES
from core.constants import STATE_1_REAL
from .constants import STATE_CHOICES
from .constants import STATE_1
class ModelX(models.Model):
user = models.ForeignKey(User)
state = models.IntegerField(verbose_name=u'state',
choices=STATE_CHOICES,
default=STATE_1)
core_state = models.IntegerField(verbose_name=u'real state',
choices=SOME_OTHER_CHOICES,
default=STATE_1_REAL)
class Meta:
ordering = ('-state',)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With