我正在尝试将一个User字段添加到模型中,但它不会在迁移文件中生成。
// models.py
from django.db import models
from django.contrib.auth.models import User
class Foo(models.Model):
"""This class represents the Foo model."""
name = models.CharField(max_length=255, blank=False, unique=True)
owner = models.OneToOneField(User,
related_name='foos',
on_delete=models.CASCADE),
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
def __str__(self):
"""Return a human readable representation of the model instance."""
return "{}".format(self.name)
我运行python3 manage.py makemigrations
并获得此输出:
// 0001_initial.py
migrations.CreateModel(
name='Foo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=255, unique=True)),
('date_created', models.DateTimeField(auto_now_add=True)),
('date_modified', models.DateTimeField(auto_now=True)),
],
),
任何人都知道该怎么做?是否应该避免使用Django提供的User对象并只创建自己的?
答案 0 :(得分:1)
我发现您的模型的第一个问题是comma
字段中有OneToOne
。删除。
然后,从官方文档中,他们使用settings.AUTH_USER_MODEL
作为参考。因此,请尝试以下代码段并执行makemigrations
和migrate
Db。
from django.db import models
from django.conf import settings
class Foo(models.Model):
"""This class represents the Foo model."""
name = models.CharField(max_length=255, blank=False, unique=True)
owner = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='foos', on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
def __str__(self):
"""Return a human readable representation of the model instance."""
return "{}".format(self.name)
希望这有帮助!