Django与其他字段的ManyToMany关系 [英] Django's ManyToMany Relationship with Additional Fields

查看:170
本文介绍了Django与其他字段的ManyToMany关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想存储一些额外的信息,自动创建,ManyToMany连接表。我该怎么做在Django?

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

在我的例子中,我有两个表:Employees和Projects。我想要存储的是每个员工在每个项目中每小时的工作量,因为这些值不一样。

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?

我发现的是,而不是方法ManyToManyField,显式地创建第三个类/表来存储这些新的信息并使用ForeignKey方法设置其与Employees和Projects的关系。我确定它会工作,但这是最好的方法吗?

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?

推荐答案

这里是你想要实现的例子:

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

如果链接中断:

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)

这篇关于Django与其他字段的ManyToMany关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆