Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django's ManyToMany Relationship with Additional Fields

I want to store some additional information in that, automatically created, ManyToMany join-table. How would I do that in Django?

In my case I have two tables: "Employees" and "Projects". What I want to store is how much each of the employees receives per hour of work in each of the projects, since those values are not the same. So, how would I do that?

What occurred to me was to, instead of the method "ManyToManyField", create explicitly a third class/table to store those new informations and to set its relationship with "Employees" and "Projects" using the "ForeignKey" method. I'm pretty sure it will work, but is this the best approach?

like image 361
rrb_bbr Avatar asked Dec 14 '10 19:12

rrb_bbr


People also ask

How do you add data to many-to-many fields in Django?

To add data into ManyToMany field with Python Django, we can use the add method. This will add the entry for the association table between my_obj and categories .

How does Django handle many-to-many relationship?

Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship. By default, this table name is generated using the name of the many-to-many field and the name of the table for the model that contains it.

How do I create a one to many relationship in Django?

One to many relationships in Django models. To define a one to many relationship in Django models you use the ForeignKey data type on the model that has the many records (e.g. on the Item model). Listing 7-22 illustrates a sample of a one to many Django relationship.

What is many-to-many field in Django?

A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.


1 Answers

Here is example of what you want to achieve:

http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships

In case link ever breaks:

from django.db import models  class Person(models.Model):     name = models.CharField(max_length=128)      def __str__(self):              # __unicode__ on Python 2         return self.name  class Group(models.Model):     name = models.CharField(max_length=128)     members = models.ManyToManyField(Person, through='Membership')      def __str__(self):              # __unicode__ on Python 2         return self.name  class Membership(models.Model):     person = models.ForeignKey(Person)     group = models.ForeignKey(Group)     date_joined = models.DateField()     invite_reason = models.CharField(max_length=64) 
like image 199
gruszczy Avatar answered Sep 20 '22 19:09

gruszczy