user3242244
user3242244

Reputation: 25

Django model structure - best practice

For a little free fruit site, I have the following model relationship:

3 classes - Apples, Strawberries, and Locations

Apples and Strawberries list all "properties" of the fruits:

class Apple(models.Model):     
    treeSize = ...
    age = ...

class Strawberry(models.Model):
    fieldArea = ...

Now I want to record all locations with the fruits. So far I have a class with locations and attributes for Apples and Strawberries, which keeps the ForeignKeys to the kind of fruits. But that can't be it. It looks very inefficient, esp. if I add multiple other fruit types. Also, I would need to check that each location has at least one of the fruit keys.

class Location(models.Model):    
     lat = ...
     lng = ... 
     appleType = models.ForeignKey(Apple, null = True)
     strawberryType = models.ForeignKey(Strawberry, null = True)

Is there a better way to design the relationships or the model structure? What would be the best practice for this problem?

Thank you for your advice!

Upvotes: 1

Views: 2340

Answers (1)

lprsd
lprsd

Reputation: 87077

This is a perfect case where you need to use the Generic Relations.

Instead of storing the Foreign Key to each one of those, you store the content type id (that recognizes Strawberries from Apples) and the object ids. You can of-course, develop this with your own conventions using the relevant strings within the Location model, but all that hard work is done for you in the django's built in Content Type Framework.

Upvotes: 2

Related Questions