【问题标题】:Django ManyToManyField Custom StructureDjango ManyToManyField 自定义结构
【发布时间】:2016-02-07 20:49:10
【问题描述】:

是否可以在Django中手动指定ManyToManyField创建的表结构?

我正在尝试将 Django 与现有数据库集成,并希望能够使用现有表中的数据。无法更改数据库的结构,因为这会破坏使用数据库的原始应用程序。

如果有帮助,这里是表定义:

class People(models.Model):
    person_id  = models.CharField(db_column='PersonId', primary_key=True)
    first_name = models.CharField(db_column='FirstName')
    ...

class PersonCats(models.Model):
    category_id  = models.IntegerField(db_column='PersonCatId', primary_key=True)
    title = models.CharField(db_column='Title', max_length=50)
    ...

class PersonCatPeople(models.Model):   #No primary key on this table
    person_cat_id = models.IntegerField(db_column='PersonCatId)
    person_id     = models.CharField(db_column='PersonId')
    ...

【问题讨论】:

    标签: sql django django-models many-to-many django-orm


    【解决方案1】:

    我在您的模型中看不到任何 ManyToMany 字段,但我认为您正在寻找 ManyToManyFieldthrough 选项。您可以指定要在两个相关表之间使用的自定义表,并且可以定义其结构(字段):

    这里有一个例子:

    from django.db import models
    
    class Person(models.Model):
        name = models.CharField(max_length=50)
    
    class Group(models.Model):
        name = models.CharField(max_length=128)
        members = models.ManyToManyField(Person, through='Membership', through_fields=('group', 'person'))
    
    class Membership(models.Model):
        group = models.ForeignKey(Group)
        person = models.ForeignKey(Person)
        inviter = models.ForeignKey(Person, related_name="membership_invites")
        invite_reason = models.CharField(max_length=64)
    

    这取自Django ManyToMany Docs

    【讨论】:

    • 我没有创建 ManyToMany 字段,因为表当前在没有它的情况下运行(虽然相当慢)。但这看起来正是我所需要的
    • 好吧,我认为这就是您自定义中间表所需要的。
    • 虽然这很理想,但会破坏使用它的主程序
    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 2013-08-03
    • 2020-07-19
    • 2020-02-02
    • 2012-03-25
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    相关资源
    最近更新 更多