I have the following code:
class Tutors(models.Model):
first_name = models.CharField(max_length=20, default=None, blank=False) #you need to add default none and blank false to enforce the Not-Null constraint
last_name = models.CharField(max_length=20, default=None, blank=False)
email = models.EmailField(max_length=254,default=None, blank=False)
birth_day = models.DateField(auto_now=False, auto_now_add=False, default=False, blank=False)
def __str__(self):
return(self.first_name ' ' self.last_name)
class ArtSubjects(models.Model):
subject_name = models.CharField(max_length=20, default=None, blank=False)
tutors = models.ManyToManyField(Tutors)
def __str__(self):
return self.subject_name
My question is, should I define many to many relationships like this? Or should I define a new class for the table?
The reason I ask is that I can get objects from the join table by querying by ArtSubjects class like so - adobeAI.tutors.all()
returns <QuerySet [<Tutors: Matt Aird>, <Tutors: Tom John>]>
But I can't think of a way for querying the join table by tutors to see what classes an individual tutor teaches.
Any advice on this?
CodePudding user response:
You can query tutors the same way. Here's an axample:
john = Tutors.objects.get(first_name="John")
john.artsubjects_set.all()
If you like to have a more readable name than _set
, add a related_name
on the ManyToManyField field:
class ArtSubjects(models.Model):
tutors = models.ManyToManyField(Tutors, related_name="teaches")
...
john.teaches.all()
You can find more details in the documentation https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/
CodePudding user response:
This can be done (see https://docs.djangoproject.com/en/3.2/topics/db/models/#extra-fields-on-many-to-many-relationships), but if you're not adding additional data to the intermediary model I wouldn't recommend it.
Django will create the intermediary model behind the scenes. In this case it would be accessible as ArtSubjects.tutors.through
.
See @Marco's answer for how to query the relationship.