Database is not changing after a migration - django

So using south, I wanted to add a new field is_private to one of my models.
Following the tutorial, after changing the models.py file, I should do this:
./manage.py schemamigration reconstructions --auto
which returns:
Added field is_private on reconstructions.Reconstruction
Created 0005_auto__add_field_reconstruction_is_private.py. You can now apply this migration with: ./manage.py migrate reconstructions
Which is great. Now next step is,
python manage.py migrate reconstructions
And that prints:
- Migrating forwards to 0005_auto__add_field_reconstruction_is_private.
> reconstructions:0005_auto__add_field_reconstruction_is_private
- Loading initial data for reconstructions.
No fixtures found.
it seems to be doing it's job. But when I afterwards check the field is_private, Django throws me an error:
Cannot resolve keyword 'is_private' into field.
Which tells me south did not changed the database at all. Why is so?
Extra information:
The model class:
class Reconstruction(models.Model):
id = models.CharField(max_length=36, primary_key=True,
editable=False)
uploader = models.ForeignKey(User, blank=True, null=True)
status = models.TextField(blank=True)
viewcount = models.IntegerField(default=0)
error_flag = models.IntegerField(default=0)
is_done = models.BooleanField(default=False)
create_date = models.DateTimeField(auto_now=True)
last_modified_date = models.DateTimeField(auto_now=True)
is_private = models.BooleanField(default=True)
The code causing the crash:
recordings = Recording.objects.filter(is_done=True).filter(is_private=False).order_by('-create_date')

Observation: you added is_private to Reconstruction, but you're trying to filter Recording objects based on that property. Perhaps this is the issue?

Related

Test a data migration ManyToMany in Django

I tried to add a field to my ManyToMany relationship models in Django.
So step by step, I created the new model and apply makemigrations and migrate.
I checked I have the new table in my postgresql database.
Now before I will add the through keyword in the ManyToMany field I want to write a function in the migration file that will copy the old data of the previous ManyToMany table to the new one with the additional field.
I followed a solution explained here:
Django migration error :you cannot alter to or from M2M fields, or add or remove through= on M2M fields
I want to test the function that will migrate the data in a test function but I don't understand what to do.
here my code:
survey/models:
class Survey(BaseModel):
name = models.CharField(max_length=256, help_text='Survey name')
user = models.ManyToManyField(User, blank=True, help_text='patient')
survey/models:
class SurveyStatus(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
survey = models.ForeignKey(Survey, on_delete=models.CASCADE)
survey_status = models.CharField(max_length=10,
blank=True,
null=True,
choices=STATUS_SURVEY_CHOICES,
)
The function I wrote that need to copy the data from the previous M2M to the new one is the following one:
def create_through_relations(apps, schema_editor):
Survey = apps.get_model('survey', 'Survey')
SurveyStatus = apps.get_model('survey', 'SurveyStatus')
for survey in Survey.objects.all():
for user in survey.user.all():
SurveyStatus(
user=user,
survey=survey,
survey_status='active'
).save()
I don't understand what is apps? because it is not recognized by python
I don't understand why i need schema_editor because it's not used
it doesn't recognized my Survey or SurveyStatus models too
when i tried to run this script with
if __name__ == "__main__":
create_through_relations(survey)
I've got this error
NameError: name 'survey' is not defined
and if i tried this function
from django.apps import apps
def create_through_relations():
Survey = apps.get_model('survey', 'Survey')
SurveyStatus = apps.get_model('survey', 'SurveyStatus')
for survey in Survey.objects.all():
for user in survey.user.all():
SurveyStatus(
user=user,
survey=survey,
survey_status='active'
).save()
when i tried to run this script with
if __name__ == "__main__":
create_through_relations()
I've got this error
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
If someone can help and explain me how to solve.thanks
1: Apps represent the different parts of your project (Django Apps)
2: You don't need it at this point. In general, it translates the models into SQL syntax.
3: python manage.py <...> does load the models for execution. Your file is trying to access data that isn't available that way.
4: The variable survey can't be found in python's main function, since you never declared it there. You need to trigger it inside your project.
5: You can test things by creating a test.py (Django Tests)
6: You don't need to transfer the data to a whole new table after changing a model, just extend the existing one and migrate the changes:
class BaseModel(models.Model):
created = models.DateTimeField('created', default=timezone.now)
changed = models.DateTimeField('changed', default=timezone.now, blank=True, null=True)
class Survey(BaseModel):
uuid = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=256, help_text='Survey name')
description = models.TextField('description', blank=True)
status = models.BooleanField(default=False) # paused/ active
class SurveyQuestion(BaseModel):
survey = models.ForeignKey(Survey, related_name='survey', on_delete=models.CASCADE)
text = models.CharField(max_length=256)
# 1 -> Text, # Integer, # ChoiceField, etc.
requested_result = models.IntegerField(default=0)
class QuestionResult(BaseModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
question = models.ForeignKey(SurveyQuestion, related_name='survey_question', on_delete=models.CASCADE)
answer = models.CharField(default='', max_length=256)

Django relation "personindustry" does not exist

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.

Django no such column even after migrations

This is my model code
class Poll(models.Model):
created_at = models.DateTimeField(auto_now=True)
edited_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=200,default="X vs Y")
description = models.CharField(max_length=200,default="A poll")
def __str__(self):
return self.title
class Item(models.Model):
poll = models.ForeignKey('Poll',on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now=True)
edited_at = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=200)
type_of = models.CharField(max_length=200)
description = models.TextField(max_length=1200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.name
You see votes in Item model right. That's a problem. I use makemigrations migrate command. But I still get no such column error.
Edit:
This is makemigrations vs_chart output
Migrations for 'vs_chart':
vs_chart\migrations\0001_initial.py:
- Create model Item
- Create model Poll
- Add field poll to item
This is migrate command output.
Operations to perform:
Apply all migrations: vs_chart
Running migrations:
No migrations to apply.
Before you add field poll to item, you may try to provide default value for ForeignKey, absence of default value may cause this issue:
poll = models.ForeignKey('Poll',on_delete=models.CASCADE, default=0)

django not nullable error on model field containing null-True

So i have a user that can post comments on effects, im linking up my models and i keep getting the non-nullable error no matter what ive tried. Everyone says it needs to have null=True. It isn't working lol. What am I not seeing here?
This is the official error:
django.db.utils.IntegrityError: NOT NULL constraint failed: effect_modules_comment__new.author_id
And my models:
class Effect_module(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=255)
description = models.TextField()
html = models.TextField(default='')
css = models.TextField(default='')
js = models.TextField(default='')
up_votes = models.IntegerField()
down_votes = models.IntegerField()
effect_author = models.ManyToManyField('UserProfile')
class UserProfile(models.Model):
user = models.OneToOneField(User)
effects = models.ManyToManyField(Effect_module)
class Comment(models.Model):
comment_author = models.ForeignKey(User, null=True)
comment = models.TextField(default='No Comment Here')
effect_object = models.ForeignKey(Effect_module)
Delete all migration scripts. Add null=True means it can be NULL in the database, blank=True means that it can be left blank in forms.
Then
python manage.py makemigrations
python manage.py migrate

Django postions: adding PositionField breaking migration

I have already tables for Vehicle and Car, Using this django-positions for postioning my items of the tables. For that i have added the positon field in both the models.
class Vehicle(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True)
position = PositionField()
And
class Car(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True)
vehicle = models.ForeignKey(Vehicle, related_name="vehicle")
position = PositionField()
makemigrations ran fine but while migrate getting following error. using postgreSQL
django.db.utils.IntegrityError: check constraint "myapp_vehicle_position_check" is violated by some row
It turns out that during the migration the SQL code checks for the value of the PositionField to be greater than or equal to 0. The default being -1 for automatic ordering the migration fails.
I haven't digged any more but as a turnaround changing the default value to something equal or above zero allow for the migration to be successful.
class Vehicle(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(max_length=50, unique=True)
position = PositionField(default=99)
Hope this helps.