Django model foreignkey field moves to a different model on makemigrations, possible bug?

  Kiến thức lập trình

I declared two models on Django 4.1.13 (tried to upgrade to 4.2 too), with MySQL 8:

class CarteraPuntos(models.Model):
    socio = models.ForeignKey("soci.Socio", on_delete=models.CASCADE, verbose_name="Socio", related_name="cartera_puntos"),
    punti = models.PositiveSmallIntegerField(blank=True,null=True, default="0")

class MovimentoPunti(models.Model):

    def __init__(self,*args,**kwargs):
        super(MovimentoPunti, self).__init__(*args,**kwargs)
        self.controllo_punti_precedenti = self.punti

    def __str__(self):
        return "{} - {} puntos".format(str(self.socio),str(self.punti))

    socio = models.ForeignKey("soci.Socio", on_delete=models.CASCADE, verbose_name="Socio", related_name="movimenti_punti")
    data = models.DateTimeField(auto_now_add=True)
    punti = models.PositiveSmallIntegerField()


and I am unable to perform this simple signal task


from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import MovimentoPunti,CarteraPuntos


@receiver(post_save, sender=MovimentoPunti)
def somma_punti_totali(sender, instance, **kwargs):
    if instance:
        if instance.controllo_punti_precedenti == instance.punti:
        else:
            id_socio = instance.socio.id
            try:
                portafoglio = CarteraPuntos.objects.get(socio_id=id_socio)
                portafoglio.punti += instance.punti
                portafoglio.save()
            except CarteraPuntos.DoesNotExist:
                portafoglio = CarteraPuntos.objects.create(socio_id=id_socio,punti=instance.punti)
            except Exception as e:
                print(e)

because I always get this error

Cannot resolve keyword 'socio_id' into field. Choices are: id, punti

which looked strange to me because if I check the attributes on the MovimentoPunti model like this

hasattr(MovimentoPunti,'socio_id')

It unsurprisingly returns True while on the contrary

hasattr(CarteraPuntos,'socio_id')

.
returns False

So I tried to change

socio_id

to

socio__id

with double underscore and later to a simpler

socio

and it still never worked.

So I went to check the migration that has been generated by Django for these two models and this is what I believe is finally a clue: the “socio” field is being created for the second model only.

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('soci', '0004_alter_socio_id'),
    ]

    operations = [
        migrations.CreateModel(
            name='CarteraPuntos',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('punti', models.PositiveSmallIntegerField(blank=True, default='0', null=True)),
            ],
        ),
        migrations.CreateModel(
            name='MovimentoPunti',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('data', models.DateTimeField(auto_now_add=True)),
                ('punti', models.PositiveSmallIntegerField()),
                ('socio', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='movimenti_punti', to='soci.socio', verbose_name='Socio')),
            ],
        ),
    ]

Why is that? Is there something I’m missing or I’m not understanding?

I finally decided to connect the two tables between them. I would just like to ask if there is something wrong to my approach or maybe an odd behavior of Django

LEAVE A COMMENT