Hi!
I have an app that's about presenting fictional simplified cities.
Please consider the following Django models:
class City(models.Model):
name = models.CharField(...)
...
TYPEGROUP_CHOICES = (
(1, 'basic'),
(2, 'extra'),
)
class BldgType(models.Model):
name = models.CharField(...)
group = models.IntegerField(choices=TYPEGROUP_CHOICES)
class Building(models.Model):
created_at = models.DateTimeField(...)
city = models.ForeignKey(City)
type = models.ForeignKey(BldgType)
other_criterion = models.ForeignKey(...)
class Meta:
get_latest_by = 'created_at'
Explanations for choosing this setup:
(1) Each city has certain buildings of a "basic" type which occur exactly once per city (examples: city hall, fire station, police station, hospital, school) and possibly dozens of buildings of "extra" type, such as dance clubs.
(2) In certain views, all buildings (regardless of city, etc.) are to be filtered according to different criteria, e.g., other_criterion
.
Problem/concern:
In a city_detail
view, I would have to loop over any buildings of "extra" type, which is OK and normal.
But I am not sure how to efficiently retrieve the city's "hospital" building, which is of "basic" type, so I must do this for every city anyway because exactly one such hospital exists in each city (this is ensured at city creation time).
There will be at most a dozen of "basic" building types, of which about half will be presented all the time.
I'm inclined towards writing convenience methods on the City model, and I face three options:
(A1) Via try
and index: .filter(...)[0]
(A2) Via try
and .get(...)
(A3) Via try
and .filter(...).latest()
But none of those seem elegant.
Or is one of these three options good to combine with some sort of caching, like in Django's get_profile()
method on the User
model? Unfortunately, I have no experience with caching yet.
Is it nuts to use the following option?
(B) specific FKs in the City model, one for each of the most important basic types
Question:
Which option makes sense the most?
Or is the schema generally faulty for this kind of scenario?
Especially regarding DB performance, what do you suggest? Do I need a completely different approach?
Please advise! :)
Thanks in advance!