Django 1.11 with PostgreSQL.
I go to migrate my site and models.py throws the error that I can't have more than one primary key. I can't see where I do (or I'm not understanding how).
class Employee(models.Model):
Aegis_ID = models.UUIDField(primary_key=True, null=False, default=uuid.uuid4, editable=False, serialize=True)
Employee_Number = models.ForeignKey('self', on_delete=models.CASCADE, related_name='Company_Employee_Number',
null=True, blank=True, max_length=6, help_text="Employee ID")
Employee_FName = models.CharField(null=True, blank=True, max_length=25, help_text="First Name")
Employee_LName = models.CharField(null=True, blank=True, max_length=25, help_text="Last Name")
Employee_Email = models.EmailField(max_length=80, blank=True, help_text="GPM Email address")
Employee_Position = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True,
related_name='Department_Employee_Position', max_length=3,
choices=EMPLOYEE_POSITION, help_text="Select position of this Employee.")
Hire_Date = models.DateField(null=True, blank=True, help_text="Enter the employee hire date.")
Employee_Division = models.CharField(max_length=2, null=True, blank=True, choices=DIVISION_CHOICES,
help_text="Assign the Audit Division for this employee.")
Employee_Region = models.CharField(max_length=3, null=True, blank=True, choices=REGION_CHOICES,
help_text="Assign the Audit Region for this employee.")
Employee_District = models.CharField(max_length=3, null=True, blank=True, choices=DISTRICT_CHOICES,
help_text="Assign the Audit District for this Employee.")
Reading the Django pages on this exact topic, it's listed as a problem resolved in 1.7 and had to do with how Django sorted the tables by class, alphabetically.
I've also tried python manage.py flush followed by makemigrations prior to migrate
So, what fields is Django / Postgres attempting to make an "id" and "primary" because I'm just not understanding, here...
According to the Django documentation regarding Automatic Primary Keys, there's the unseen is id = models.AutoField(primary_key=True) but I also understood that if you assign the primary_key=True to a field, this did not apply
In your above model Multiple primary keys for table “app_employee” are not allowed.
It is not coming because you have
Aegis_ID = models.UUIDField(primary_key=True, null=False, default=uuid.uuid4, editable=False, serialize=True)
Because in django documentation it is clearly specified that
Django Documentation
Field.primary_key
If True, this field is the primary key for the model.
If you don’t specify primary_key=True for any field in your model, Django will automatically add an AutoField to hold the primary key, so you don’t need to set primary_key=True on any of your fields unless you want to override the default primary-key behaviour.
primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object.
I have tried your model on my project and it is working absolutely fine.
For simplicity I removed other fields
models.py
from __future__ import unicode_literals
from django.db import models
import uuid
class Employee(models.Model):
Aegis_ID = models.UUIDField(primary_key=True, null=False,default=uuid.uuid4, editable=False, serialize=True)
Employee_Number = models.ForeignKey('self', on_delete=models.CASCADE, related_name='Company_Employee_Number',
null=True, blank=True, max_length=6, help_text="Employee ID")
Employee_FName = models.CharField(null=True, blank=True, max_length=25, help_text="First Name")
Employee_LName = models.CharField(null=True, blank=True, max_length=25, help_text="Last Name")
Employee_Email = models.EmailField(max_length=80, blank=True, help_text="GPM Email address")
and when I did
(venv) astikanand#Developer-PC:~/firstsite$ python manage.py makemigrations
Migrations for 'employee':
employee/migrations/0001_initial.py
- Create model Employee
and then
(venv) astikanand#Developer-PC:~/firstsite$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, employee, sessions
Running migrations:
Applying employee.0001_initial... OK
so it is working fine.
You need to do is
Either you recreate your app or simply start your project all over again, may be some dependency issues or something. But your code for model Employee is all ok.
It is quiet possible that you changed primary keys and/or references to other models/tables and some legacy dependencies remained in the migration files.
Please refer to the official Django documentation for reverting past migrations. You do not have to restart your project to remove dependencies.
python manage.py makemigrations --empty yourappname
That is it. Then check 0001_initial.py file under migrations folder in your app to make sure all dependencies have been removed. It should look like:
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('yourappname', '0001_initial'),
]
operations = [
]
Related
After learning most of my primary keys did not have to be hardcoded in Django models, I decided to remove them all. In order to have Django-admin up and running I had to solve a few issues first, which I did by deleting all migrations files.
Once those issues were out of the way, after making migrations and migrating sucessfully again, while in Django admin trying to add data to a particular model, right after clicking the add button I got this error message:
Traceback (most recent call last):
File "C:\Users\fsoar\urban_forest_box\virtualenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedColumn: column app_species_catalog_nome_popular.id does not exist
LINE 1: ...188_sync_1" NO SCROLL CURSOR WITH HOLD FOR SELECT "app_speci...
This lead to a series of exceptions which ledd to another series of exceptions of which the last erros message was:
psycopg2.errors.InvalidCursorName: cursor "_django_curs_17188_sync_1" does not exist
models.py is a bit long, so I am pasting only the main model of this app, which is the one I was using to add data when it happened, and which speaks for itself regarding my Python/Django skills level :)
I would like to understand what is going on, and I imagine it will take several months before I get to that, but most important, I would like to fix it first, so as to keep my learning journey going.
# ARVORE
class Img_Arvore(models.Model):
img_arvore = models.ImageField(upload_to=r'urban_forest_django_project\uploads\img_arvores_completas')
class Meta:
verbose_name = "Foto da árvore"
verbose_name_plural = "Fotos da árvore"
class Arvore(models.Model):
nome_cientifico = models.CharField("Nome científico", max_length=200, help_text="Nome científico completo", primary_key=True)
nomes_populares = models.ManyToManyField(Nome_Popular, verbose_name="Nomes populares")
estados_de_conservacaos = (
('EX', 'Extinta'),
('EW', 'Extinta no ambiente silvestre'),
('CR', 'Criticamente em perigo'),
('EN', 'Em perigo'),
('VU', 'Vulnerável'),
('NT', 'Quase ameaçada'),
('LC', 'Menos preocupante'),
('DD', 'Dados insuficientes'),
('NE', 'Não avaliado')
)
estado_de_conservacao = models.CharField("Estado de conservação", max_length=50, choices=estados_de_conservacaos)
botanic_description = models.TextField('Descrição botânica', blank=True)
create_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(blank=True, null=True)
taxonomia = models.OneToOneField(Taxonomia, on_delete=SET_NULL, null=True, blank=True)
biotipo = models.ForeignKey(Biotipo, on_delete=SET_NULL, null=True, blank=True)
dendrometria = models.ForeignKey(Dendrometria, on_delete=SET_NULL, null=True, blank=True)
peculiaridades = models.ForeignKey(Peculiaridade, on_delete=SET_NULL, null=True, blank=True)
caule = models.ForeignKey(Caule, on_delete=SET_NULL, null=True, blank=True)
raiz = models.ForeignKey(Raiz, on_delete=SET_NULL, null=True, blank=True)
folha = models.ForeignKey(Folha, on_delete=SET_NULL, null=True, blank=True)
flor = models.ForeignKey(Flor, on_delete=SET_NULL, null=True, blank=True)
fruto = models.ForeignKey(Fruto, on_delete=SET_NULL, null=True, blank=True)
distribuicao_estadual = models.ManyToManyField(UF_Brasileira, blank=True)
distribuicao_regional = models.ManyToManyField(Regiao_Brasileira, blank=True)
dominio_fitogeografico = models.ManyToManyField(Bioma_Brasileiro, blank=True)
vegetacao_encontrada = models.ManyToManyField(Vegetacao_Brasileira, blank=True)
maiores_informacoes = models.ForeignKey(Link_Externo, on_delete=SET_NULL, null=True, blank=True)
class Meta:
verbose_name = "Árvore"
verbose_name_plural = "Árvores"
def __str__(self):
return self.nome_cientifico
Did you also drop (delete) your database?
Your database changes with migrations, So if you delete migrations and you dont drop your database, database will be confused because it is not synced with your django app. Try to run it on another database, but dont forget to makemigration and also migrate.
You should think of migrations as a version control system for your database schema. makemigrations is responsible for packaging up your model changes into individual migration files - analogous to commits - and migrate is responsible for applying those to your database.
For more information : https://docs.djangoproject.com/en/3.2/topics/migrations/
I have a below model,
class PersonIndustry(DFModel):
person = models.ForeignKey(
Person, models.DO_NOTHING, blank=True, null=True)
industry = models.CharField(max_length=50, blank=True, null=True)
class Meta:
db_table = ‘person_industry'
My postgres database contains person_industry table.
When I registered this model in admin site it is giving me below error,
ProgrammingError at /admin/apis/personindustry/
relation "personindustry" does not exist
LINE 1: SELECT COUNT(*) AS "__count" FROM “personindustry"
I am quite confuse why it is searching for personindustry instead of person_industry. Please advise.
I also had this problem recently, what I did is:
# Clear migrations history
python manage.py migrate --fake APP_NAME zero
Then, delete the migrations files and .pyc files except for init.py. Now, make migrations:
python manage.py makemigrations APP_NAME
Now, fake the intial migrate. That will fake the intial table with name personindustry:
python manage.py migrate --fake-initial
*Note:- Feel free to ask. Refs
My meta class was creating problem,
class DFModel(models.Model, metaclass=DFModelBase):
class Meta:
abstract = True
I changed it to default,
class PersonIndustry(models.Model):
person = models.ForeignKey(
Person, models.DO_NOTHING, blank=True, null=True)
industry = models.CharField(max_length=50, blank=True, null=True)
class Meta:
db_table = ‘person_industry'
It is loading now.
I am working on a django (1.8.6) site that involved two applications now. One is a custom user model with basic registration / login / logout functionality, the second is a feedback application. I want to have a foreign key relationship from a feedback to the user that submitted it.
When I try to run ./manage.py migrate I get the following error.
django.db.utils.ProgrammingError: relation "customauth_user" does not exist
This is of course since the database table does not YET exist. If I remove the related field, everything works fine. Here is my code.
My user model:
class User(AbstractBaseUser):
username = models.CharField(_('username'), max_length=100, unique=True)
email = models.EmailField(('email address'), max_length=254)
first_name = models.CharField(_('first name'), max_length=50)
last_name = models.CharField(_('lat_name'), max_length=50)
receive_newsletter = models.BooleanField(_('receive_newsletter'), default=False)
referral_id = models.CharField(_('referral id'), max_length=40)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'first_name', 'last_name']
And the model from my feedback form:
class Feedback(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='feedback')
title = models.CharField(max_length=100)
message = models.CharField('Users message', max_length=1024)
reviewed = models.BooleanField('Reviewed by staff', default='NEW', choices=FEEDBACK_STATUS_CHOICES, max_length=10)
jira_ticket_created = models.BooleanField('Created a Jira ticket to track this feedback.',
default=False)
jira_ticket_number = models.CharField(max_length=10, blank=True, null=True)
class Meta:
db_table = 'feedback'
def __str__(self):
return str(self.timestamp) + ' ' + self.title
I have configured my user model in settings, added both applications, and in my installed applications my applcaition with my custom user model is first.
Any thoughts?
Thanks
Craig
You need to add a dependency in your feedback migration to the customauth app. See the migrations docs.
You should use python manage.py makemigrations
and then python manage.py migrate
Im working on a Django project using south for schema migrations.
I have the following scenario:
schema
class Book(model.Models):
name = models.CharField(max_length=255, blank=True)
bid = models.IntegerField(blank=True, null=True)
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
book_id = models.ForeignKey(Book, null=True, to_field="bid", db_column="bookID")
I wanna change Author model to the following:
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
book = models.ForeignKey(Book, null=True, db_column="book_id")
but without loose data. I want to search each book by its bid and assign the one found to the new field in Author model.
Thanks
You'll have to do a 3 migrations. A schemamgiration that adds the new book FK, then a data migration and then a schemamigration to delete and rename the fields.
So you'll want to change your models.py file to this:
class Book(model.Models):
name = models.CharField(max_length=255, blank=True)
bid = models.IntegerField(blank=True, null=True)
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
book_id = models.ForeignKey(Book, null=True, to_field="bid", db_column="bookID")
# You don't need the db_column="book_id" since that's what it does at the DB level by default.
# I'm not sure if things will break if you name it book with another field as book_id.
book_new = models.ForeignKey(Book, null=True)
Then run python manage.py schemamigration APP_NAME auto
Then run ```python manage.py datamigration APP_NAME populate_book_id
Then edit the newly created data migration and loop through the Author instances setting the new book field with the book_id field. Don't forget to remove the book field values in the backwards method.
Then change your models.py file to the following:
class Book(model.Models):
name = models.CharField(max_length=255, blank=True)
bid = models.IntegerField(blank=True, null=True)
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
# You don't need the db_column="book_id" since that's what it does at the DB level by default.
book = models.ForeignKey(Book, null=True)
Then run python manage.py schemamigration APP_NAME auto
You'll want to check this last schemamigration to make sure it's renaming book_new to book and not dropping and creating columns. Here's an answer that explains how to change it.
I have two models formatted as follows:
class Attachment(models.Model):
# ...
class Message(models.Model):
# ...
attachment = models.ForeignKey(Attachment, blank=True, default=None, null=True)
# ...
I have tried various solutions found every where online...but cannot make it work!
Here are some of the combinations I have tried:
blank=True
null=True
blank=True, null=True
default=None
blank=True, null=True, default=None
etc.
I keep getting the following error whenever I try to save a message with no attachment.
IntegrityError: myapp_message.attachment_id may not be NULL
I am using SQLite if that is significant. Why isn't what I am doing working?
did you modify your model after doing syncdb? If that's the case, you should delete your table and syncdb again.