本文介绍了如何在Django/Mysql中建立一对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何在Django/Mysql中建立一对多关系?

I am trying to understand how to make a one to many relationship in Django/Mysql?

这是models.py(下面的代码)

class Flora2Estado(models.Model):
    estado = models.OneToOneField(Estados, models.DO_NOTHING, primary_key=True)
    especie = models.ForeignKey('Listaflor', models.DO_NOTHING)
    class Meta:
        managed = False
        db_table = 'flora2estado'
        unique_together = (('estado', 'especie'),)


class Listaflor(models.Model):
    especie = models.OneToOneField(Flora2Estado, models.DO_NOTHING, primary_key=True)
    familia = models.ForeignKey(Familia, models.DO_NOTHING, blank=True, null=True)
    nome = models.CharField(db_column='especie', max_length=255, blank=True, null=True)  # Field renamed because of name conflict.
    class Meta:
        managed = False
        db_table = 'listaflor'

class Estados(models.Model):
    estado_id = models.AutoField(primary_key=True)
    estado_nome = models.CharField(max_length=100, blank=True, null=True)
    class Meta:
        managed = False
        db_table = 'estados

推荐答案

我认为您想要做的是通过另一个名为Flora2Estado的类在Listaflor和Estados之间建立Many2Many关系. Django M2M关系

I think that what you want to do is a Many2Many relation between Listaflor and Estados through another class called Flora2Estado. Django M2M relation

class Estados(models.Model):
    estado_id = models.AutoField(primary_key=True)
    estado_nome = models.CharField(max_length=100, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'estados'


class Listaflor(models.Model):
    especie_id = models.AutoField(primary_key=True)
    nome = models.CharField(db_column='especie', max_length=255, blank=True, null=True)
    estados = models.ManyToManyField(Estados, through='Flora2Estado')

    class Meta:
        managed = False
        db_table = 'listaflor'


class Flora2Estado(models.Model):
    estado = models.ForeignKey(Estados, on_delete=models.DO_NOTHING)
    especie = models.ForeignKey(Listaflor, on_delete=models.DO_NOTHING)

    class Meta:
        managed = False
        db_table = 'flora2estado'
        unique_together = (('estado', 'especie'),)

这篇关于如何在Django/Mysql中建立一对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:08