[Fixed]-Django model choices using other models

1👍

i also want each of these events to be models so that they can be viewed in their own space.

I would start off with an easier approach. As long as your individual events do not have totally different fields it will make things much easier to handle. You could just use a field event_type on your events table:

from django.db import models

# Do not call your model Schedule because that's what the whole table
# represents. The django models define only one entity of it.
# So Event would be a suitable name.
class Event(models.Model):
    EVENT_CHOICES = (
        ('meeting', 'Meeting'),
        ('vacation', 'Vacation'),
        ('birthday', 'Birthday'),
        # [...]
    )

    user = models.ForeignKey(User)
    time = models.DateTimeField()
    event_type = models.CharField(max_length=30, choices=EVENT_CHOICES)

To get your schedule you can do this:

schedule = Event.objects.all()

Now you can see, why Schedule is not a good name for this model. You only have one schedule consisting of all the events from your event model.

Then in your views you can filter the events e.g. like this:

birthdays_of_greg = Events.objects.filter(user__username='greg', event_type='birthday')

No need for a lot of different models in this simple use case. You can create a view that only shows birthdays, vacation etc. or only events for a certain user or a combination of this.

If you need to dynamically create event types you can create an EventType model and replace the event_type CharField with a ForeignKey to that:

from django.db import models


class Event(models.Model):
    # all your event fields

    event_type = models.ForeignKey('EventType')

class EventType(models.Model):
    name = models.CharField(max_length=50)

If you want to get really advanced you can use generic relations. This allows you to attach any model to an event with a generic foreign key.

👤trixn

0👍

I would just add an event_category field to your Schedule model with choices of “reminder”, “birthday”, etc. Then you can filter by event category: Schedule.objects.filter(event_category__exact='birthday').

If you really want a separate model for each event category then you can use a OneToOneField to link the records together:

class Birthday(models.Model):
    event = models.OneToOneField(Schedule, on_delete='models.CASCADE')
    ...

Leave a comment