I was just wondering why you need a Many-to-Many Relationship using through, if you just could use a separate Model?
For Example:
class Test(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
class Indicator(models.Model):
name = models.CharField(max_length=100)
target_value = models.IntegerField()
class TestResult(models.Model):
test = models.ForeignKey(Test)
indicator = models.ForeignKey(Indicator)
actual_value = models.IntegerField()
timestamp = models.DateTimeField(auto_now_add=True)
Why should I define a Many-to-Many Relationship? Thanks
Django will automatically generate a table to manage many-to-many relationships. You might need a custom “through” model. The most common use for this option is when you want to associate extra data with a many-to-many relationship.
A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.
The through attribute/field is the way you customize the intermediary table, the one that Django creates itself, that one is what the through field is changing.
This field can be useful as a primary key of an object if that object extends another object in some way. For example – a model Car has one-to-one relationship with a model Vehicle, i.e. a car is a vehicle. One-to-one relations are defined using OneToOneField field of django.
You should add the ManyToMany attribute for three reasons:
First of all with this attribute you are explicitly declaring the many to many relstion thus correctly modeling your domain objects. This is very important because anybody seeing your models will understand the relations - if you don't have the ManyToMany attribute the reader will be confused on what you intended to do. After all, a central point in django philosophy is that "explicit is better than implicit"! In your case you should add an indicators = ManyToMany('Indicator', through='TestIndicator') attribute to the Test model.
Furthermore, the ManyToMany attribute will help you creating queries involving the related models without needing to use the intermediate object. For instance you could get all tests having a particular indicator name ( I know this can be done also through the ForeignKey but explicit is better than implicit)
Finally, adding the ManyToMany attribute to one of the models you can create inline admin forms to easily edit the relation. For instance in your case you'd add an inline in your TestAdmin through which you'd be able to add Indicators to this Test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With