clime
clime

Reputation: 8885

Django: modelling relations

In my app, there is a model "Image" and couple of models that an image can relate to (Event, Place, Member). I am considering two ways of modelling the image relations. The first one is to put relation field in Image for each related model (the field will be either ForeignKey or ManyToManyField). The second way is to put field "images" to each model that can have associated images (in case of some models it will be just one image). Which way is more recommended?

# the first way
class Member(models.Model):
  name = models.CharField('name', max_length=128)

class Event(models.Model):
  name = models.CharField('name', max_length=128)

class Place(models.Model):
  name = models.CharField('name', max_length=128)

class Image(models.Model):
  title = models.CharField('title', max_length=128)
  members = models.ManyToManyField(Member)
  place = models.ForeignKey(Place)
  event = models.ForeignKey(Event)


# the second way
class Image(models.Model):
  title = models.CharField('title', max_length=128)

class Member(models.Model):
  name = models.CharField('name', max_length=128)
  images = models.ManyToManyField(Image)

class Event(models.Model):
  name = models.CharField('name', max_length=128)
  images = models.ManyToManyField(Image)

class Place(models.Model):
  name = models.CharField('name', max_length=128)
  images = models.ManyToManyField(Image)

I could also use generic relations (third way) or I could make models like EventImage, PlaceImage, MemberImage (fourth way) but I have already decided these would not work for me that well.

Upvotes: 0

Views: 63

Answers (1)

ykaganovich
ykaganovich

Reputation: 14964

If your relationship is Many-to-one, then the proper way to model it is with ForeignKey.

For Many-to-many relationships, it's less clear on which model to define one. Django documentation says the following:

It doesn’t matter which model has the ManyToManyField, but you should only put it in one of the models – not both.

Generally, ManyToManyField instances should go in the object that’s going to be edited on a form. In the above example, toppings is in Pizza (rather than Topping having a pizzas ManyToManyField ) because it’s more natural to think about a pizza having toppings than a topping being on multiple pizzas. The way it’s set up above, the Pizza form would let users select the toppings.

Upvotes: 2

Related Questions