THIS IS MY MODEL FILE
from django.db import models
class Donor(models.Model):
Donor_name = models.CharField(max_length=150),
Donor_status = models.IntegerField(),
Donor_city = models.CharField(max_length=50),
Donor_group = models.CharField(max_length=10),
Donor_phone = models.CharField(max_length=12),
Donor_mail = models.EmailField(max_length=50)
THIS IS MY MIGRATION
Generated by Django 2.0.2 on 2018-03-30 09:19
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Donor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
)
Why are other fields ignored ?
using Django version 2 with MySQL.
The commas at the end of the lines cause Python to treat them as tuples. Remove them.
class Donor(models.Model):
Donor_name = models.CharField(max_length=150)
Donor_status = models.IntegerField()
Donor_city = models.CharField(max_length=50)
Donor_group = models.CharField(max_length=10)
Donor_phone = models.CharField(max_length=12)
Donor_mail = models.EmailField(max_length=50)
Once you have made this change, you can run makemigrations again and Django should include your new fields. If you haven't run the migration that creates the modlel yet, you could remove the migration file before doing this. You can use python manage.py showmigrations to check whether the migration has already been run.
Note that in Django, the recommendation is to use lowercase_with_underscores for your field names, e.g. donor_name and donor_status.
Related
Python 3.10.4
Django 4.0.5
PostgreSQL 14
When I start "python manage.py makemigrations" i got the file "0001_initial.py" but all Fields, except autofields, are missing.
models.py
from django.db import models
# Create your models here.
class Username(models.Model):
#id = models.AutoField(primary_key=True)
username: models.CharField(max_length=100)
class Carrier(models.Model):
#id = models.AutoField(primary_key=True)
carriername: models.CharField(max_length=100)
desc: models.TextField()
0001_initial.py
# Generated by Django 4.0.5 on 2022-06-29 13:18
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Carrier',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
migrations.CreateModel(
name='Username',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
],
),
]
First, you must know that Django By default adds the id field to the models ...
Try to Delete the migration file and
you must use the = not the :
so it will be like this
class Username(models.Model):
username=models.CharField(max_length=100)
class Carrier(models.Model):
carriername = models.CharField(max_length=100)
desc = models.TextField()
rerun manage.py makemigrations and it Should work
I created a dummy project just to test the new field JSONField of Django but the column doesn't not appear to be created (I am using Postgresql).
class Author(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
slug = models.SlugField()
details = models.JSONField()
class Meta:
verbose_name = "Author"
def __str__(self):
return self.name
If i go to the database, the column is not created -- screenshot
When i go to the admin view page of the table Author i get the following error -- screenshot
The error in the admin panel is understandable: you cannot view a column that does not exist. Do you guys have the same error? I can't find this error with JSONField anywhere.
Thanks
Note: This is my first post.
EDIT I create all the fields in the same time. Migration file:
# Generated by Django 3.1.3 on 2020-11-20 10:35
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('description', models.TextField()),
('slug', models.SlugField()),
('details', models.JSONField()),
],
options={
'verbose_name': 'Author',
},
),
]
Migrated with sucess:
Migrations for 'blog':
blog/migrations/0001_initial.py
- Create model Author
check that you migration was applied to the right database
Scenario:
I have a model, Customer
class Customer(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
company = models.CharField(max_length=100)
and now I updated the company attribute witha ForeignKey relationship as below,
class Company(models.Model):
name = models.CharField(max_length=100)
location = models.CharField(max_length=100)
class Customer(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
company = models.ForeignKey(Company)
What I need is, when the new migrations applied to the DB,corresponding Company instance must automatically generate and map to the company attribute of Customer instance.Is that possible? How can I achieve this ?
Let's start from your original model and do it step by step.
class Customer(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
company = models.CharField(max_length=100)
First you would have to keep the original field and create a new one, to be able to restore the old data afterwards.
class Customer(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
company = models.CharField(max_length=100)
_company = models.ForeignKey(Company)
Now you can create a first migration with manage.py makemigrations. Then you will have to create a data migration. Create the migration using manage.py makemigrations yourapp --empty and update the generated file:
from django.db import migrations
def export_customer_company(apps, schema_editor):
Customer = apps.get_model('yourapp', 'Customer')
Company = apps.get_model('yourapp', 'Company')
for customer in Customer.objects.all():
customer._company = Company.objects.get_or_create(name=customer.company)[0]
customer.save()
def revert_export_customer_company(apps, schema_editor):
Customer = apps.get_model('yourapp', 'Customer')
Company = apps.get_model('yourapp', 'Company')
for customer in Customer.objects.filter(_company__isnull=False):
customer.company = customer._company.name
customer.save()
class Migration(migrations.Migration):
dependencies = [
('yourapp', 'xxxx_previous_migration'), # Note this is auto-generated by django
]
operations = [
migrations.RunPython(export_customer_company, revert_export_customer_company),
]
The above migration will populate your Company model and Customer._company field according to Customer.company.
Now you can drop the old Customer.company and rename Customer._company.
class Customer(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
company = models.ForeignKey(Company)
Final manage.py makemigrations and manage.py migrate.
Sure, but you have to do three migrations and the fields cant be named the same thing as both need to exist at the same time. If you already have removed the company field in your real database you are SOL and will have to fix them manually.
First, add the Company model in a normal db migration, then do a data migration and have it run after the first db migration, then do another db migration removing the company field from the Customer model.
The db migrations you can do with manage.py makemigrations as usual, just add something like below in a migration file between them, here i named the new company ForeignKey field to company_obj
def fix_companies(apps, schema_editor):
Company = apps.get_model("myapp", "Company")
Customer = apps.get_model("myapp", "Customer")
for c in Customer.objects.all():
company, _ = Company.objects.get_or_create(name=c.name)
c.company_obj = company
c.save()
def rev(apps, schema_editor):
# the reverse goes here if you want to copy company names into customer again if you migrate backwards.
pass
class Migration(migrations.Migration):
dependencies = [
('myapp', 'XXXX_migration_that_added_company_model'),
]
operations = [
migrations.RunPython(fix_companies, rev),
]
Something to note is if you are going through a cycle of renaming/ deprecating fields, using RunPython would leave you pointing to old model fields that wouldn't exist anymore after you are done with your field changes.
To avoid this, you might want to go with RunSQL instead.
# Generated by Django 3.2.3 on 2022-02-09 04:55
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("<your_app>", "<0006_migration_name>"),
]
operations = [
migrations.RunSQL(f"""
update public.<table_name> set new_field = old_field + some_magic;
"""
),
]
Docs.
'authorid' is a foreign key to the Django 'User' model. After running 'makemigrations' and 'migrate' I can not see this field in the sqlite shell.
Here are my models,
class TopicModel(models.Model):
topic = models.CharField(max_length = 100)
topicAuthor = models.CharField(max_length = 100)
authorid = models.ForeignKey(User, related_name = 'id_of_author')
views = models.PositiveIntegerField(default = 0)
def __str__(self):
return self.topic
class PostModel(models.Model):
post = HTMLField(blank = True, max_length = 1000)
pub_date = models.DateTimeField('date published')
author = models.CharField(max_length = 30)
topicid = models.ForeignKey(TopicModel, related_name = 'posts')
def __str__(self):
return self.post
As you can see postmodel also has a foreign key to the topicmodel and there is no problem with this foreign key.
After migration the migrate file 0001_initial.py looks like this,
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import tinymce.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='PostModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('post', tinymce.models.HTMLField(blank=True, max_length=1000)),
('pub_date', models.DateTimeField(verbose_name='date published')),
('author', models.CharField(max_length=30)),
],
),
migrations.CreateModel(
name='TopicModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('topic', models.CharField(max_length=100)),
('topicAuthor', models.CharField(max_length=100)),
('views', models.PositiveIntegerField(default=0)),
('authorid', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='id_of_author', to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='postmodel',
name='topicid',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='crudapp.TopicModel'),
),
]
In the sqlite shell the postmodel shows the field with the foreign key, which is topicid_id
sqlite> PRAGMA table_info(crudapp_postmodel);
0|id|integer|1||1
1|pub_date|datetime|1||0
2|author|varchar(30)|1||0
3|topicid_id|integer|1||0
4|post|text|1||0
But when I do the same with the topicmodel, the field with the foreign key doesn't exist, so there is no authorid field.
sqlite> PRAGMA table_info(crudapp_topicmodel);
0|id|integer|1||1
1|topic|varchar(100)|1||0
2|topicAuthor|varchar(100)|1||0
3|views|integer unsigned|1||0
Solution: As suggested by Alasdair I deleted the sqlitedb file and changed the fields from from topicid and authorid to topic and author.
Your current migration should create the foreign keys. My guess is that you updated the migration file after you had already created the crudapp_topicmodel table in the database.
If you don't have any important data yet, the easiest fix is to delete your sqlite file and rerun ./manage.py migrate.
I have a project written with Django 1.6 and that uses South migrations, and I trying to move it to Django 1.7. So I started from the instructions indicated here.
Deleted south from INSTALLED_APPS.
Removed old migrations files.
Ran ./manage.py makemigrations.
At this point I got django.db.migrations.graph.CircularDependencyError.
Here are my models:
customer.models.py:
class Customer(models.Model):
name = models.CharField(
max_length=128,
)
class Department(models.Model):
customer = models.ForeignKey(
'customer.Customer',
related_name='departments',
)
name = models.CharField(
max_length=64,
)
class Representative(models.Model):
user = models.ForeignKey(
'userprofile.User',
related_name='representatives',
)
department = models.ForeignKey(
'customer.Department',
related_name='representatives',
)
userprofile.models.py:
class User(AbstractBaseUser, PermissionsMixin):
customers = models.ManyToManyField(
'customer.Customer',
blank=True,
null=True,
)
That caused in initial migration for customer application a swappable dependency:
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
As it was recommended here, I edited initial migration for userprofile and commented lines related with customer:
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
#('customer', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('first_name', models.CharField(max_length=128, error_messages={b'min_length': 'El campo "Nombres" debe tener al menos %(limit_value)d caracteres (actualmente tiene %(show_value)d).'}, verbose_name='nombres', validators=[django.core.validators.MinLengthValidator(3)])),
('last_name', models.CharField(max_length=128, error_messages={b'min_length': 'El campo "Apellidos" debe tener al menos %(limit_value)d caracteres (actualmente tiene %(show_value)d).'}, verbose_name='apellidos', validators=[django.core.validators.MinLengthValidator(3)])),
('email', models.EmailField(unique=True, max_length=75, verbose_name='correo electr\xf3nico')),
#('customers', models.ManyToManyField(to='customer.Customer', null=True, verbose_name='clientes relacionados', blank=True)),
],
bases=(models.Model,),
),
]
ran ./manage.py migrate and created another migration that adds a customer field:
class Migration(migrations.Migration):
dependencies = [
('customer', '0001_initial'),
('userprofile', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='customers',
field=models.ManyToManyField(to='customer.Customer', null=True, verbose_name='clientes relacionados', blank=True),
preserve_default=True,
),
]
But when I run ./manage.py migrate userprofile --fake, I get an error
Running migrations:
No migrations to apply.
Your models have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
On the other hand, without this migration my tests fail:
OperationalError: no such table: userprofile_user_customers
My error was to run ./manage.py makemigrations userprofile, instead of running ./manage.py makemigrations userprofile --empty. In the first case Django understood it like a migration that adds contracts field (which it is) and for the second case, if I ran ./manage.py migrate userprofile it fails with:
django.db.utils.ProgrammingError: relation "userprofile_user_customers" already exists
So I had to:
Copy the content of the last migration:
class Migration(migrations.Migration):
dependencies = [
('customer', '0001_initial'),
('userprofile', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='customers',
field=models.ManyToManyField(to='customer.Customer', null=True, verbose_name='clientes relacionados', blank=True),
preserve_default=True,
),
]
Delete that migration.
Run ./manage.py makemigrations userprofile --empty.
Paste and run ./manage.py migrate userprofile --fake.