Reputation: 1283
I am attempting to add a User field to a model, but it's not being generated in the migration file.
// 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)
I run python3 manage.py makemigrations
and get this output:
// 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)),
],
),
Anyone have an idea what to do here? Should one avoid using the Django-supplied User object and just create your own?
Upvotes: 1
Views: 28
Reputation: 88499
The very first problem with your model I found is, there is a comma
in your OneToOne
field. Remove that.
Then, from the official doc, they are using settings.AUTH_USER_MODEL
as the reference. So, try the following snippet and do makemigrations
and migrate
the 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)
Hope this helps !
Upvotes: 1