如何在ManyToMany表(Django)中添加列 [英] How to add column in ManyToMany Table (Django)

查看:480
本文介绍了如何在ManyToMany表(Django)中添加列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Django Book的例子中,我明白我是否创建了如下所示的模型:

From the example of Django Book, I understand if I create models as following:

from xxx import B

class A(models.Model):
    b = ManyToManyField(B)

Django将创建一个超过表A的新表(A_B),它有三列:

The Django would create a new table(A_B) beyond Table A, which has three columns:


  • id

  • a_id

  • b_id

但现在我要添加一个新列表A_B,因此如果我使用普通的SQL,会很容易,但现在有人可以帮我吗?我在这本书中找不到任何有用的信息。

But now I want to add a new column in the Table A_B, thus would be very easy if I use normal SQL, but now anyone can help me how to do? I can't find any useful information in this book.

推荐答案

使用django也很简单!您可以通过使用来定义自己的多个中介表

It's very easy using django too! You can use through to define your own manytomany intermediary tables

文档提供了一个解决您的问题的示例:

Documentation provides an example addressing your issue:

Extra fields on many-to-many relationships

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __unicode__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __unicode__(self):
        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)

这篇关于如何在ManyToMany表(Django)中添加列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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