Duplicate model field in Django - python

A duplicate model field is giving me trouble (no such table appname_modelname when I run my webpage). Whenever I do ./manage.py migrate appname, it gives me "duplicate field". I checked my models.py, there is only one of them there. How do I delete that duplicate field? It seems no matter what I do, it stays. I've tried:
Deleting the database
Deleting migrations folder in app folder
Doing ./manage.py sqlclear south and then dropping the south_migrationhistory table in the dbshell
./manage.py schemamigration appname --initial, ./manage.py migrate appname --fake
I've run out of ideas.
class Document(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True, default=None)
identity = models.CharField(max_length=255, default=None, null=True)
user = models.ForeignKey(User, null=False)
user_id = models.IntegerField(User, null=True)
docfile = models.FileField(upload_to=_upload_path, storage=fs) # upload_to is a path inside the storage path
def get_upload_path(self,filename):
return str(self.user.id) + '/' + str(date.today()) + '/' + filename

You can't do this, for your user foreign key, Django ORM will create a database field named user_id (your foreign key field name plus _id) to use it as a FK in the database.
You don't have to create this field yourself (the ORM will take care), even if you need it, change the name of the attribute user or user_id.
From the documentation:
Behind the scenes, Django appends "_id" to the field name to create its database column name. In the above example, the database table for the Car model will have a manufacturer_id column. (You can change this explicitly by specifying db_column) However, your code should never have to deal with the database column name, unless you write custom SQL. You’ll always deal with the field names of your model object.

Not sure but problem causing here in these two line
user = models.ForeignKey(User, null=False)
user_id = models.IntegerField(User, null=True)
Better to use "related name" attribute to avoid the duplicate error as in database "user" will be added as user_id.
user = models.ForeignKey(User, related_name="id_user") # Change the related field as your convenience
user_id = models.IntegerField(null=True, related_name="user_id")
Check if this resolve your issues

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.

Delete 2 model different objects which reference each other as foreign keys

We have two Django models:
class Project(models.Model):
project_title = models.CharField(max_length=30)
owner = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING)
class User(models.Model):
usernmae = models.CharField(max_length=50)
active_project = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING, related_name='current_project')
I have a user with object (with id say 692). And this user created a project with id=12345, therefore these owner field will get have this particular referenced.
I want to delete that user. But it shows error that
delete on table "app_user" violates foreign key constraint
This is expected as on_delete=models.DO_NOTHING, was set. One way I found out was using on_delete=models.CASCADE.
Question: How should I go about deleting the user (692) without changing the model definition(having to re-run migration)?
Doing it manually by deleting the project first, leads to the same foreign-key error, as owner field is User object.
How to handle this mutual foreign key relationship while deleting, as deleting any one of those two throws the foreign-key exception?
Update
Some correction in the model definition username is the field name instead of usernmae (typo). And the foreignkey for project is Project not the User model.
class Project(models.Model):
project_title = models.CharField(max_length=30)
owner = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING)
class User(models.Model):
username = models.CharField(max_length=50)
active_project = models.ForeignKey(Project, null=True, on_delete=models.DO_NOTHING, related_name='current_project')
IF you really don't want to make a migration (any specific reason?) and if you are ok with doing this manually this time. Then you have two options:
Go into the admin panel and manually change the User field in the project instance to a different user or to NULL. Now you should be able to delete the User instance since it's not referred anymore into the project.
If that worked, you can then delete the project instane as well.
Curios if this will work, let me know!

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

Not Null Constraint Failed - null=True already set

I am changing my register model so that there is a foreign key referencing a location. What I want to achieve, is to have a relationship where the Register model can have 0 to many locations.
Originally I set a manytomany field which I realised was a mistake as it gives each Register all of the locations in existence. I just want a subset for each Register.
My model now looks like:
class Register(AbstractBaseUser, models.Model):
username = models.CharField(max_length=20,default='',blank=True)
password = models.CharField(max_length=80,default='',blank=True)
email = models.CharField(max_length=255,default='',blank=True)
#Added 2nd May
#locations = models.ManyToManyField(Location)
#3rd May change to foreign key
locations = models.ForeignKey(Location,on_delete=models.CASCADE, blank=True, null=True, default='')
USERNAME_FIELD = 'username'
The model referenced is:
class Location(models.Model):
locationname = models.CharField(max_length=80,default='',blank=True)
address = models.ForeignKey(Address, on_delete=models.CASCADE)
geolocation = models.ForeignKey(GeoLocation, on_delete=models.CASCADE, default='')
When I try to migrate I get the error below. I have ran makemigrations and if I run it again it states there are no changes.
"NOT NULL constraint failed: register_register.locations_id"
I have been searching other posts and it suggested adding the null=True argument which I have added, but I still get this error. I can't find any posts where this has been done and it still gives this error.
Purging the data from the database using manage.py flush allowed me to re-migrate the projects.
I realised that I had made a mistake with the relationship and had the Foreign key on the wrong table, it needed to be on location so that was fundamentally the issue.

Multiple default values specified for column "uid" of table in Django 1.8

I am creating a Django Application, and my models.py is :
class Registration(models.Model):
uid = models.AutoField(primary_key=True, default=0)
uname = models.CharField(max_length=100, blank=False, null=False)
upassword = models.CharField(max_length=100, blank=False, null=False)
uphone = models.IntegerField(blank=True, null=True)
uhid = models.ForeignKey('Hood', blank=False, null=False, default='ABC')
uemail = models.EmailField(blank=False, null=False, default='abc402#nyu.edu')
uintro = models.TextField(null=True, blank=True)
uphoto = models.ImageField(upload_to='', blank=False, null=False, default='static/img/natural_join_is_inner_join.png')
uhood = models.CharField(max_length=10, null=True)
uaddress = models.CharField(max_length=100, default='ABC')
# django automatically uses the media root which you have declared in your settings, define that to `upload_to`
def __unicode__(self):
return self.uname
I then run the following commands:
python manage.py makemigrations
python manage.py migrate
But it is showing me an error:
multiple default values specified for column "uid" of table
"registration_registration"
Can anyone help me to resolve this issue? The other links on stack overflow are not of much help!
When I removed id uid field then Django is showing me:
You are trying to add a non-nullable field 'id' to registration without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
The issue is why I should provide a default value for id which django automatically creates?
UPDATE: I have deleted the migration folder, so I was resolve the above issue but now I am getting an error:
"Error creating new content types. Please make sure contenttypes "
RuntimeError: Error creating new content types. Please make sure
contenttypes is migrated before trying to migrate apps individually.
You should not have defined a default value for uid in the first place. It's an AutoField, it gets an auto-incremented value from the database.

Categories