vishes_shell February 2016

Best practice for storing custom value instead of foreignkey?

The situation is quite simple.

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

class Event(models.Model):
    ...
    event_type = models.ForeignKey('EventType')

There is need to give an opportunity to enter custom event_type in CharField. The reason why EventType class is separate is that there will be a lor of lookups on that field. And lookups will be ONLY on ForeignKey entries (Not the custom values).

To sum up: Is there a better solution to store custom event_type than declaring an aditional field custom_event_type = models.CharField()?

Answers


Tony February 2016

You could still save all event types with the same model, but use an additional field to tell whether you want to include an EventType in your search results:

class EventType(models.Model):
    name = models.CharField()
    include_in_search = models.BooleanField()

class Event(models.Model):
    ...
    event_type = models.ForeignKey('EventType')

If you create a database index sorted by include_in_search and then by name, I bet you really won't notice any difference in the time to make a lookup.

You did not write all the specifications you need, but you may want to set the name field to be unique or even use it as primary key.

Post Status

Asked in February 2016
Viewed 1,009 times
Voted 12
Answered 1 times

Search




Leave an answer