Django ORM: dynamic columns from reference model in resultset
Creating an app to track time off accrual. Users have days and days have types like "Vacation" or "Sick"
Models:
DayType
- Name
UserDay
- Date
- DayType (fk to DayType)
- Value (+ for accrual, - for day taken)
- Note
- T开发者_Python百科otal
I'm trying to generate the following resultset expanding the daytypes across columns. Is this possible in the ORM, or do I have to build this in code?
I think you'd have an easier time by not putting the DayType in another model. Is there a specific reason you went that route?
If not, you should take a look at the choices
attribute of Django's fields
. Your code would look something like this:
class UserDay(models.Model):
DAY_TYPES = (
('vac', 'Vacation'),
('ill', 'Sick'),
)
day_type = models.CharField(max_length=3, choices=DAY_TYPES)
# Other fields here...
It seems like a somewhat cleaner solution since the types of days they have aren't likely to change very often. Plus, you can avoid a DB table and FK lookup by storing the values this way.
精彩评论