I'm sure this has been asked before, but I cannot find the answer. In django, if I have this model
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
How would one populate this model with a default Person entry when the first migrating the field?
I'm not talking about default values for the fields, but for default entries in the database.
thanks
You can make a data migration, that follows on the migration where you create the Person object. You can first let Django write the "skeleton" of the migration, this can be done with:
python manage.py makemigrations --empty appname
Next Django will make a file. In that file you can add RunPython item to the operations list. This then obtain the historical model (the model at that moment of the migration), where you then create a Person object in the database. For example with:
from django.db import migrations
class Migration(migrations.Migration):
def create_person(apps, schema_editor):
Person = apps.get_model('appname', 'Person')
Person.objects.create(first_name='will', last_name='mendil')
dependencies = [
('appname', 'migrationname'),
]
operations = [
migrations.RunPython(create_person)
]
I am adding a new field to a model:
class Abc(models.Model):
...
slug = models.SlugField(unique=True)
During Makemigrations I provided an empty string once for all. And then Migrate failed because of duplicate key Key (slug)=() is duplicated.
The follows are what I have tried to solve the problem. makemigrations were all OK but migrate failed due to the same reason.
1) Remove unique=True and migration again
2) Remove the slug field and migration again
3) Set unique=False and migrate again
The database can not be deleted. I am stuck and left without options. Any suggestions?
You are having this problem because there are at least two records in the table that have the same slug.
To fix this, you could do the following steps
Create a data migration. ./manage.py makemigrations <app_name> --empty
In the migration file, add django migration's RunPython operation in the file. An example would be something like the snippet below.
from __future__ import unicode_literals
from django.db import models, migrations
from django.utils.text import slugify
def forwards(apps, schema_editor):
Abc = apps.get_model('app', 'Abc')
for obj in Abc.objects.all():
if len(obj.slug) == 0:
obj.slug = slugify(obj.field1)
obj.save()
class Migration(migrations.Migration):
dependencies = [
('app', '0003_Abc'),
]
operations = [
migrations.RunPython(forwards, reverse_code=migrations.RunPython.noop),
]
Add the unique=True to the field.
Create the migration. ./manage.py makemigrations <app_name>
Migrate your database. ./manage.py migrate <app_name>
I'm learning Django from Tango with Django but I keep getting this error when I type:
python manage.py makemigrations rango
python manage.py migrate
This is the output:
django.db.utils.IntegrityError: UNIQUE constraint failed: rango_category__new.slug
Models.py:
from django.db import models
from django.template.defaultfilters import slugify
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __unicode__(self):
return self.title
The reason for this constrain could be that you didn't have any field called slug in Category class when you have initially migrated it (First Migration), and after adding this field in the model, when you ran makemigrations, you have set default value to something static value(i.e None or '' etc), and which broke the unique constrain for the Category's table's slug column in which slug should be unique but it isn't because all the entry will get that default value.
To solve this, you can either drop the database and migration files and re-run makemigrations and migrate or set a unique default value like this:
slug = models.SlugField(unique=True, default=uuid.uuid1)
Edit:
According to Migrations that add unique fields, modify your migration file to overcome unique constrain. For example, modify your migration file (which added the slug field to the model) like this:
import uuid
from app.models import Category # where app == tango_app_name
class Migration(migrations.Migration):
dependencies = [
('yourproject', '0003_remove_category_slug'),
]
def gen_uuid(apps, schema_editor):
for row in Category.objects.all():
row.slug = uuid.uuid4()
row.save()
operations = [
migrations.AddField(
model_name='category',
name='slug',
field=models.SlugField(default=uuid.uuid4),
preserve_default=True,
),
migrations.RunPython(gen_uuid),
migrations.AlterField(
model_name='category',
name='slug',
field=models.SlugField(default=uuid.uuid4, unique=True),
),
]
I got a field with attribute unique, which was not unique [eg 2-time same value]
python3 manage.py migrate --fake
then
python3 manage.py makemigrations
python3 manage.py migrate
this did the trick
This means a slug should be unique. You may have some data in your model. You need to delete all the data in that model and you need to migrate again.
In this situation, you have two ways to fix the error;
You need to delete it from the Django admin site. More often than not, it may give an error when you are trying to open the model.
Open command prompt
move to project -> py manage.py shell -> from yourappname.models import modelname -> modelname.objects.delete()
Here if you define a product manager for your model. Then you have to define a delete function. Later you should makemigrate, migrate and continue with the second way
I just met this simiilar error: Django UNIQUE constraint failed. I tried examine the code for very long time, but didn't solve it. I finally used SQLiteStudio to examine the data, and found the data is problematic: I unintentionally added two SAME instances which violates the UNIQUE constraint. To be frank I haven't thought the error could be this naive and simple, and because so it took me a lot of time to find out!
I had the same problem and tried all the suggested answers. What finally worked for me was, after I defined the slug field as a URL in models, and ran the makemigrations. I edited the file in makemigrations adding a random number at the end of a basic URL, like this
Generated by Django 3.2.3 on 2022-02-02 20:58
from django.db import migrations, models
from random import randint
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_remove_post_slug1'),
]
operations = [
migrations.AddField(
model_name='post',
name='slug',
field=models.URLField(blank=True, default='http:/salpimientapa.com/' + str(randint(100000,999999))),
),
]
After I ran
python manage.py migrate
I edit the slug as a SlugModel and ran the makemigrations and migrate again
What worked for me was going to the admin and changing the value of duplicate slug, before running the migrations again.
Just delete the last migration in the migration folder
Then run
python manage.py makemigrations
python manage.py migrate
I faced the same issue and solved by populating my slugfied thro' the admin with unique values and without leaving any of them blank.
Basically: You add the field without unique=true in one operation, make a data migration that generates the correct shortuuids for you, and then change the field too unique again.
i have this error too ,
i did delete my database in djangoProject ( for example db.sqlite3 )
and then run
python manage.py makemigrations
python manage.py migrate
It's an Integrity Error probably because the migration will temper with the already exiting data in the database.
I had this error and here's what I did:
Enter in the project folder directory
Open the python interpreter
py manage.py shell
Import your Models
from yourappname.models import model
Delete existing data records in the model
model.objects.all().delete()
Exit the Python Interpreter
exit()
.
Another thing you could do is to set unique="false" on the affecting field. I think this should work; not so sure.
Currently programming in Python Django 1.4. In my files I have written CREATE TABLE functions for productos and clientes to be created in the MySQL database. When I checked with python manage.py sqlall ventas (ventas being the parent directory of productos and clientes), it outputs that snippet of code. However, when I tried to access them under localhost admin, I got the
1146, "Table 'demo.ventas_cliente' doesn't exist" error. And these 2 tables do now show up in MySQL.
Initially I had dropped these 2 tables because there were some DB errors. I ran syncdb again but does not seem to retrieve those 2 tables. What seems to be wrong?
I strongly suggest you don't type MySql commands directly, this may throw you many errors in the future. To create tables in Django you must create models. For example:
1) In ./Yourproject/apps/yourDBName create __ init __.py
2) in settings.py under "installed apps" add your new app. Example: yourproject.apps.yourapp
4) execute "python manage.py runserver"
5) create models.py into your new app
6) now you can create your models like that:
class myTable(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
7) if you want to access your new table from the admin, create admin.py in your app and type:
from django.contrib import admin
from models import myTable
admin.site.register(myTable)
#here, you can add more tables to the admin in the future
also, if you need to use foreign keys:
class parentTable(models.Model):
idParent = models.AutoField(primary_key=True)
parentName = models.CharField(null=False)
class childTable(models.Model):
idChild = models.AutoField(primary_key=True)
MyParentName = models.ForeignKey(parentTable, to_field='parentName')
childName = models.CharField(null=False)
MORE INFO: https://docs.djangoproject.com/en/dev/topics/db/models/
I have a model like this
class Task(models.Model):
name = models.CharField(max_length=100)
...
class TaskForm(forms.ModelForm):
class Meta:
model = Task
Then,I added couple of fields to Task and did migration
python manage.py schemamigration myapp --initial
python manage.py migrate myapp
Migration is successfully done.
Now,as an afterthought,I added a help_text to the model field
class Task(models.Model):
name = models.CharField(max_length=100,help_text='choose a good one')
...
Do I have to do the schemamigration again?I think his change doesn't affect the database table.
You need not run migrate again.
Django do not save help_text to the databases, help_text exists in application level, Django render it to HTML.