J. Doe
J. Doe

Reputation: 19

Models in Python Django not working for Many to Many relationships

I am trying to create the proper Django model that could fit the following reqs:

Person Class has 1 to many relations with the Address Class

Person Class has many to many relations with the Group Class

Book Class contains the collections of the Persons and the Groups

This is my code:

class Person(models.Model):
    first_name = models.CharField(max_length=15)
    last_name = models.CharField(max_length=20)

    def __str__(self):
        return  self.first_name+ ' - ' + self.last_name


class Address(models.Model):
    person = models.ForeignKey(Person)  
    address_line = models.CharField(max_length=200)

    def __str__(self):
        return self.address_line


class Group(models.Model):
    group_name = models.CharField(max_length=12)
    persons = models.ManyToManyField(Person)

    def __str__(self):
        return self.group_name

class Book(models.Model):
     record_name = models.CharField(max_length=12)
     person = models.ForeignKey(Person )  
     group = models.ForeignKey(Group )  

     def __str__(self):
         return self.record_name

However it's not correct: 1) A Group can now contain multiple Persons but the Persons do not contain any Group. I am not sure if I should add to the Person class the following code:

groups = models.ManyToManyField(Group)

2) The Book class now contains only 1 record of Person & Group per Book record.

3) When I added the Foreign Keys to the models, I removed on_delete tag:

person = models.ForeignKey(Person, on_delete=models.CASCADE())

because it does not compile it, asking for some params.

I know how to make all this for C#, but I am a kinda stucked with this simple task in Python/Django.

Upvotes: 1

Views: 818

Answers (1)

idik
idik

Reputation: 882

1) The ManyToMany field should appear only in one of the models, and by looks of things you probably want it in the Person model. Its important to understand that the data about the ManyToMany field is saved in a differant table. Django only allows this field to be visable through buth models (so basiclly, choose where it is move convinient).

2)By the look of your structure I will suggest you use a ManyToMany field through a different table. here is an example:

class Activity(models.Model):
    name = models.CharField(max_length=140)
    description = models.TextField(blank=True, null=True)

class Route(models.Model):
    title = models.CharField(max_length=140)
    description = models.TextField()
    activities_meta = models.ManyToManyField(Activity, through = 'RouteOrdering')

class RouteOrdering(models.Model):
    route = models.ForeignKey(Route, on_delete=models.CASCADE)
    activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name='activita')
    day = models.IntegerField()
    order = models.IntegerField(default=0)

that way the data is binded to the ManyToMany field

Upvotes: 1

Related Questions