简体   繁体   中英

Foreign key missing from migrations

I have the model trade/ Trade .py:

from datetime import datetime
from django.db import models
from home.models import Player


class Trade(models.Model):
    buyer = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='buyer'),
    buyee = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='buyee'),
    date = models.DateTimeField(default=datetime.now)

Model home/ Player .py:

from django.contrib.auth.models import User
from django.db import models
class Player(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='user')
    value = models.IntegerField(default=1500)
    owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name='owner', blank=True, null=True)

A Trade happens between 2 Player s. That is, the buyer and buyee fields in Trade are foreign keys to Player .

Now, when I make migrations for the Trade model, this is what I get:

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Trade',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('date', models.DateTimeField(default=datetime.datetime.now)),
            ],
        ),
    ]

Why are the 2 foreign key fields missing from the migration?

This happened due to the comma at the end of each field in the Trade class. Remove the commas and it will work.

class Trade(models.Model):
    buyer = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='buyer')
    buyee = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='buyee')
    date = models.DateTimeField(default=datetime.now)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM