开发者

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

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?

Django ORM: dynamic columns from reference model in resultset


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜