Python Django OperationalError no such column model.id - python

When trying to access my model via the Admin webpage using Django, I get an Operational Error stating "no such column: model_name.id"
I did my migrations and all but I am still getting the same error.
I assume I am getting this error because I had to change the name of my model. Since, I had to delete my database and migrations and had to re migrate all of my changes.
I originally got the error of not having a table built so I used some SQL to build the table and now I am stuck with a missing column under the name "id". Thanks in advance.
My models:
class PersonalUse(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
phone_number = models.IntegerField()
verification = models.IntegerField()
messages = models.BooleanField(default=False)
message_sent = models.BooleanField(default=False)

Related

django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table

I am having a problem with Django 2.2.7 and postgresql 12 using the command "python manage.py migrate".
When I execute it, the process fails with the following error:
django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "clients_clients"
I understand that this error indicates that when a field is used as a foreing key in another table, this field must be unique.
My model clients in Django is:
class Clients(models.Model):
name = models.CharField(max_length=60, unique=True)
document_num = models.CharField(max_length=15)
phone = models.CharField(max_length=15, blank=True)
email = models.EmailField(max_length=30, blank=True)
instagram = models.CharField(max_length=30, blank=True)
address = models.TextField(max_length=100, blank=True)
The model with the foreing key to the field "name" of clients_clients is:
class Budgets(models.Model):
date = models.DateField(error_messages={'null': "You must set a date"})
title = models.CharField(max_length=50, unique=True)
client = models.ForeignKey(Clients, null=True, on_delete=models.SET_NULL, to_field='name')
price = models.DecimalField(default=0, decimal_places=2, max_digits=10)
observations = models.TextField(max_length=200, blank=True)
As is shown above, the field "name" in model "Clients" is set as unique=True. But in spite of that, the error mentioned is shown.
Anyone can help me to understand why?
I could fix the problem.
The problem is as I copied my Django application from an existing installation to a new one, a lot of migration files exist in the app folders.
First, I had to delete all the files inside the "migrations" folders in any app of my Django project (taking care of not delete the init.py file).
Then I ran again the commands:
python manage.py makemigrations
and
python manage.py migrate
Now, everything works fine.

NOT_NULL contraint failed when adding foreign key to model in django

I am making a notes app. When I try to create a foreign key to link the user and its notes, im getting an error while using
python manage.py migrate
. I am very new to foreign keys, I looked at the Django docs, this is how they created a foreign key.
here's the code :
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.body[0:50]
here's the error :
django.db.utils.IntegrityError: NOT NULL constraint failed: new__api_note.author_id
Your issue is that that there are existing notes in the database that do not have a author_id field, but you have not set a default value and neither allowed to to be kept blank. Thus it's a IntegrityError to add the field.
You can solve this in 2 ways:
Allow the field to be blank
Delete the last migration in your migrations folder
Edit the author field like this:
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
Run makemigrations and migrate
Set a default value for the field
Delete the last migration from the migrations folder. You can also edit it but simply deleting it is easiest
Run makemigrations again
During make migration, it will prompt you if you want to provide a default value for the field. Select "Provie a one of value for now"
Type models.User.objects.all().first() or alternatively some other "defalt" author for existing notes
Run migrate
You can also solve the problem by removing all existing notes from the database

Why am I getting an integrity error django?

I am building a django web app with a custom user model. At the end of the sign up process when I submit the form an integrity error occurs.
Here is the error:
Exception Type: IntegrityError
Exception Value: NOT NULL constraint failed: accounts_user.job_history_id
This error indicates that the field in the custom user model named job_history cannot be null. However such a field does not even exist.
Here is my custom user model:
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
username = models.CharField(max_length=40, unique=True)
avatar = models.ImageField(blank=True, null=True)
date_joined = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username", "password"]
def __str__(self):
return "#{}".format(self.username)
def get_short_name(self):
return self.username
I have no idea what this error is referring to and why it is occurring. I added the field named job_history at a previous point but have since deleted it and updated the database accordingly. This error only began to occur when I was fiddling around with the Job and User models in order to achieve a field capable of storing the users previously completed jobs. Further details are available in this stackoverflow questions.
Why is the integrity error occuring and how do I fix it?
The error says that your job_history field is still in the database and for some reason your migrations didn't work. So you need to look why your migration didn't work. You can try doing fake initial migration:
python manage.py makemigrations app_name
python manage.py migrate --fake-initial
I'm quite sure this should help, but if this also doesn't help you always can go directly to your DB and delete the job_history_id column from DB

Django migration not working with postgresql?

I have models :
class Keyword(models.Model):
keyword_name = models.CharField(max_length=40)
keyword_category = models.ForeignKey(Category, null=True)
class Category(models.Model):
category_name = models.CharField(max_length=40)
active = models.BooleanField(default=False)
But when I create migrate this model it give error
django.db.utils.ProgrammingError: relation "main_Keyword" does not
exist
I have try many ways but it's not working.Firstly this project i'm create on local using sqlite database but when I migrate database to postgresql then it give this error. what is my mistake?
EDIT :
Request Method: GET Request
URL: http://127.0.0.1:8000/admin/main/keyword/ Django Version: 1.9.6
Exception Type: ProgrammingError Exception Value: column
main_keyword.keyword_category_id does not exist LINE 1:
...ain_keyword"."id", "main_keyword"."keyword_name", "main_keyw...
^
IMO, from the error message, the models seem to be registered in the admin.py.
Delete the code in admin.py and try the migration again.

Django models foreign key not recognizing 'QueryString' BaseObject

I am currently working on a Django 1.5.2 project within a Docker instance that speaks with a mysql database in a separate Docker instance. I am trying to create a Many to Many relationship between two tables by creating a middle table that contains two foreign keys that point to the two tables that need connecting. The problem arises when I run python manage.py syncdb and it spits out the following error to the terminal: NameError: name 'QueryString' is not defined. QueryString is clearly defined in my models.
Here are my Models...
class Tag(models.Model):
name = models.CharField(max_length=100)
class QueryStringTab(models.Model):
tag = models.ForeignKey(Tag, related_name='querystringtab')
querystring = models.ForeignKey(QueryString, related_name='querystringtab')
class QueryString(BaseObject):
"""
Query string holds an SQL statement and query properties for execution
"""
server_id = models.IntegerField()
schema = models.CharField(max_length=255, blank=True)
query = models.CharField(max_length=60000)
variables = models.TextField(blank=True)
created_by = models.ForeignKey(User, related_name='queries_created')
updated_by = models.ForeignKey(User, related_name='queries_last_edited')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField()
touched_by = models.CharField(max_length=1000)
config = models.TextField(blank=True)
runs_started = models.IntegerField(default=0)
runs_completed = models.IntegerField(default=0)
runs_completed_duration = models.IntegerField(default=0) # total number of seconds spent running this query to completion
formats = "pretty_html html json prettyjson csv excel tableau".split()
Noteworthy points...
1) It is recognizing the Tag model just fine.
2) Could it have something to do with the fact that QueryString is a BaseObject
3) It is successfully creating the Tag table in the mysql database
Can anyone find anything obvious that I am doing wrong?
The declaration of QueryStringTab is before the one for QueryStringTab; so when Python evaluates the first, it has not yet seen any definition for the second and therefore reports a NameError.
Django allows you to use a string target than a class object in cases like this:
querystring = models.ForeignKey('QueryString', related_name='querystringtab')
Or, you could simply move the definition of QueryStringTab to the end.

Categories