0

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

enter image description here

Here is models.py (code below)

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
Shadow
  • 33,525
  • 10
  • 51
  • 64
Jay
  • 109
  • 8

1 Answers1

2

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'),)
acg
  • 188
  • 6
  • Hey! Thanks a lot for your reply. I've used the code you suggested, but i got an error: ERRORS: : (admin.E109) The value of 'list_display[6]' must not be a ManyToManyField. Do you how can I fix it? Once again, thanks a lot – Jay Nov 18 '20 at 21:55
  • 2
    This is happening because in your admin.py you are trying to use list_display with the M2M field and is not allowed. This other post can help you to fix it [link](https://stackoverflow.com/questions/18108521/many-to-many-in-list-display-django) – acg Nov 18 '20 at 22:04
  • thank you so much for your help! It worked! You saved me! – Jay Nov 19 '20 at 16:28