[Answered ]-Django model relations and dividing models into few tables in larger project

1πŸ‘

βœ…

The question you want to ask yourself is:

  • Does one SetOfServices contain multiple SingleServices –> YES
  • Does one SingleService show up in multiple different SetOfServices? –> YES

If your result to these questions is two times YES the relationship is a many-to-many.

class SetOfServices(models.Model):
    set_of_services = models.ManyToManyField(SingleService)
    # price_of_set --> does this really need to be stored in database?
   
    @property
    def price_of_set(self):
        return sum([service.price for service in self.set_of_services.all()])

Now you want to ask yourself:

  • Does a Purchase allow buying multiple SetOfServices (this is dependent on your choice)? –> NO
  • Is a SetOfServices bought by multiple Purchases? –> YES

YES YES –> ManyToMany
NO YES –> OneToMany –> ForeignKey

class Purchase(models.Model):
    client = OneToOneField(client)  
    order = models.ForeignKey(SetOfServices, on_delete=models.CASCADE, blank=True, null=True)
    # same advice as above for price = ???

    @property
    def price(self):
        return self.order.price_of_set

To be honest I feel like your setup of models is already kinda stable. I can’t tell you how to divide models at runtime of a project. I’ve never done it.

Let me know how it goes!

Edit after comment of OP

Depending on your "staring point" you can access the price inside of your templates. Here some examples:

<h1>Object = Purchase</h1>
{{ object.price }}
<h1>Object = SetOfServices</h1>
{{ object.price_of_set }}
<h1>Object = SingleService</h1>
{{ object.price }}
πŸ‘€Tarquinius

Leave a comment