In my Django model, I want to use the text choices from another model, but I don't want to use it as a foreign key, because I want the whole list of weekdays before any Day object exists.
If I use it as a foreign key, I will need to create Day object first.
Can anyone help to solve this?
class Day(models.Model):
class Weekdays(models.TextChoices):
MONDAY = "Monday"
TUESDAY = "Tuesday"
WEDNESDAY = "Wednesday"
THURSDAY = "Thursday"
FRIDAY = "Friday"
SATURDAY = "Saturday"
SUNDAY = "Sunday"
store = models.ForeignKey(Store, on_delete=models.DO_NOTHING)
weekday = models.CharField(max_length=9, choices=Weekdays.choices)
class School(models.Model):
weekday = ???
You can reuse the Weekdays
from the Day
model, with:
class Day(models.Model):
# …
pass
class School(models.Model):
weekday = models.CharField(max_length=9, choices=Day.Weekdays.choices)
Since the choices do not really "belong" to any of the two models, it might make more sense to define these outside the two class, so:
class Weekdays(models.TextChoices):
MONDAY = "Monday"
TUESDAY = "Tuesday"
WEDNESDAY = "Wednesday"
THURSDAY = "Thursday"
FRIDAY = "Friday"
SATURDAY = "Saturday"
SUNDAY = "Sunday"
class Day(models.Model):
store = models.ForeignKey(Store, on_delete=models.DO_NOTHING)
weekday = models.CharField(max_length=9, choices=Weekdays.choices)
class School(models.Model):
weekday = models.CharField(max_length=9, choices=Weekdays.choices)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.