Django Model Some problems - django

I'm Shimul,
I've been working with Django for about 1 year - but I'm having a project problem with a problem -
When I create a model - e.g.
class postmodel(models.Model):
title = models.CharField(max_length=255)
blog_slug = models.SlugField(max_length=255,unique=True)
Then I migrated the model.
after migrating my Model [blog_slug] field I want to delete.
When I migrate the model again - and then an error occurs in the database.
The error is that the field named [blog_slug] was not found,
I don't want to delete my database - I want to [blog _slug] remove it.
What can be done to avoid this problem -

If you are in development mode and you want to delete blob_slug, remove that field from models and remove database (sqlite probably), pycache files, migations documents ( do not delete migration folder and init.py files)
Then exit virtualenv and run server again.

Related

unique_together does not replace primary key

In my Django app, I want to insert a record with a composite primary key. Apparently this should be possible by making use of "unique_together". I'm quite sure this code was working in the past, but for some reason it does not seem to be working now. This code used to run on a Linux VM, and now I'm hosting it in Google App Engine. However I don't see how this can be the cause for this error.
class TermsAndConditionsDocument(models.Model):
organization = models.ForeignKey(Organization, on_delete=models.CASCADE, verbose_name=_("Organization"))
language = models.CharField(_('Language'),choices=LANGUAGE_CHOICES, max_length=5, help_text=_("The language of the content."))
content = models.TextField()
class Meta:
unique_together = ('organization', 'language')
The error:
IntegrityError at /transactions/settings/terms_and_conditions
null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, nl-BE, <p>B</p>, 10).
According to what I've read, using "unique_together" should cause Django to not need or include an ID as primary key. I checked the database, and the ID field DOES exist. I do not understand where the database constraint and the ID field are still coming from?
Apparently, as pointed out in the comments, a primary key "id" field is always added, even if you don't need it. It's supposed to get out of your way, so you don't even notice its existence. In my case, it required me to give it a value when I created a new record, which is not how things are supposed to work.
A while back I migrated this database from one Postgres database to another Postgres database. I used an SQL dump and load method for this. Some sequences seem to have been lost during that migration.
Because there are no sequences, some fields now lacked autoincrement capabilities, explaining the IntegrityError on insertion.
In order to fix this, I did the following:
1) Export the current data:
manage.py dumpdata > data.json
2) Drop your database and create a new empty one.
3) Run database migrations:
manage.py migrate
4) Load the data again, excluding some default data already recreated by Django.
manage.py loaddata --exclude auth.permission --exclude contenttypes data.json
This procedure seems to have recreated the sequences while also keeping the data.
The unique_together only creates a DB constraint (https://docs.djangoproject.com/en/2.2/ref/models/options/#unique-together).
You could create a custom primary key with the option primary_key https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.Field.primary_key but you could only do that for one field.
But I suggest to just keep the auto increment id field, this works better with Django.
For the error are you saving a model? or doing a raw import?

Can't add new field in the django model

Django 2.0
I've created a model in Blog app,
class Category(models.Model):
field1 = models....
field2 = models....
field3 = models....
and after some time I want to add a new field in that model.
class Category(models.Model):
field1 = models....
cover_pic = .models....
field2 = models....
field3 = models....
I followed this answer. But it gives me the following error.
django.db.utils.OperationalError: (1054, "Unknown column 'blog_category.cover_pic' in 'field list'")
That answer is from 2014 and for an old Django version.
The workflow for adding new fields is simple:
Write code for the field in your model.
Run command manage.py makemigrations.
Run command manage.py migrate.
This is all in the documentation.
Since, you already followed that answer and have run the manage.py --fake command, you have messed up your db state a little bit.
To recover, do this:
Go to your "blog" app's "migration" folder.
Look at the names of the migration files. They should look like 0001_category_field1.py, 0002_category_cover_pic.py.
The faked migration will be the one with name something like 0002_category_cover_pic.py. Note its number, like 0002.
Now you'll have to move back to the previously applied migration. So, if the faked migration number is 0002, the previously applied migration will be 0001.
Now run this command - manage.py migrate --fake myapp 0001. Note the number of the migration file. You'll have to fake another migration back to the previously applied migration file.
Now run command - manage.py migrate myapp.
This should fix your problem.
If you're problem is not solved yet and you don't have important data in your database, I would suggest start your database from fresh. Delete all your database tables, then delete all the migration files inside your app_name/migration folders. Now run the two commands and start developing.
python manage.py makemigrations
python manage.py migrate
Now you will have a fresh database and you are good to go. From next time try to follow the way mentioned in the above comment.
If you are adding a new field in the Django model and after deploying to any environment , you are getting error while accessing the field.
Error:
"1054, Unknown column"
Although i also was not able to figure out how to resolve it but i came up with a work around.
I created a column manually in the DB .
I added the same field in the model.
Again tried to access the field and it worked like a charm.
I hope it helps your case.

Django migration involving RenameModel not working

I have been successfully using makemigrations and migrate in Django 1.7 for altering, adding and removing fields. Unfortunately, I cannot get it working when trying to rename an intermediate model. I.e. I have two models A and B, linked through a many-to-many field through model X, and I would like to rename X to Y.
Running manage.py makemigrations does not detect the rename, instead it deletes X and adds Y. But that's not the problem. I replaced Django's autogenerated scripts with:
[ migrations.RenameModel(old_name='X',new_name='Y'),
migrations.AlterField(
model_name='Y',
name='a',
field=models.ForeignKey(related_name=b'Y', to='B'),
)]
This gives me the following error:
ValueError: Lookup failed for model referenced by field b: X
So I guess it's struggling with a 'through' relation that contains the old name of the model. I tried adding a migration command to change that relation, updating it to the new name of the intermediate model, but that didn't help either.

django added a new class in a model

This thing never happened to me before,as i never had to create another class in the model field after doing syncdb already. I am now reviewing one of my past projects and i need to add another class in the models.py file. I have very little understanding of south, its more like a procedural one.
when i do this
./manage.py sql app_name
it showls the new table but when i run the server it throws an operational error 'no such table found'. Am i missing something this whole time?? Is there a way??
according to this
./manage.py sql app_name
just print sql statement for create table.
you can write it in a file
./manage.py sql app_name > command.sql
and feed it to database. for example if use postgresql you can use:
psql -U user db_name < command.sql

Before syncdb, delete field from standard Django model

This is a follow-up question on Delete field from standard Django model. In short: a field can be dynamically deleted from a model that is already created, in this case the field User.email . So field email would be deleted from User without changing the code for User. See code below for example.
I can dynamically delete a a field from a model(1), but that happens when the server starts and is undone when it exists. Since syncdb doesn't require the server to be running, and generally seems to ignore the deletion code (somehow), this approach doesn't prevent the field from appearing in the database(2).
Is there a way to do delete the field from the model (without changing the file it's in, as it's a Django model), in a way that also makes it not appear in the database?
Thanks in advance!
Mark
EDIT: I problem is not that I am deleting the text "m = models.IntegerField()" from the model file and want the field removed from the database. The problem is that I am using the code below to remove a field from a model that has already been declared in another file. I do not think that creating a migration with South for every time I run syncdb is a solution(3).
Additional information:
1) Currently, the code is in models.py, but I suppose Where to put Django startup code? works.
2) I can delete it on post_syncdb signal with custom query, but I hope for something more elegant... Or elegant at all, more accurately.
3) If it even works at all, because obviously syncdb is still seeing the 'removed' field), so I think South would to as it's still somehow there.
This is the code (models.py):
class A(models.Model):
m = models.IntegerField()
for i, f in enumerate(A._meta.fields):
if f.name == 'm':
del A._meta.fields[i]
break
class B(A):
n = models.IntegerField()
for i, f in enumerate(B._meta.fields):
if f.name == 'm':
del B._meta.fields[i]
break
EDIT: I checked (with print) and the deletion code is executed on syncdb. It is executed before tables are created
django does a lot of meta class magic and i would guess that the meta class is responsible for defining the database table to back your model. Subsequently just deleting the field is not enough to alter the generated table.
as several people have pointed out, south is the way to deal with these problems.