Django migration not picking up all the model fields - django

I created a new Django project on Windows 10, with the latest python and Django. After creating the model with a number of tables/models on one model it skipped some fields. After retrying it would not create a new migration script. I looked at the initial 0001_initial.py and the fields were missing in that file. I later added a single new field and that field migrated property but not the missing fields. All other models were successfully updated in the initial migration. This happens to be a SQLite DB.
The model that is missing fields:
class articles(models.Model):
""" articles"""
title = models.CharField (max_length=500)
teaser = models.CharField (max_length=500)
summary = models.CharField (max_length=1500)
byline = models.CharField (max_length=250)
category = models.SmallIntegerField
articlenote = models.CharField (max_length=1000)
author = models.CharField
publishedDate = models.DateTimeField
articleStatus = models.CharField(max_length=4)
articleText = models.TextField
last_update= models.DateTimeField
def __str__(self):
return self.name
The missing fields are : category, author, publishedDate, articleText
Interesting after trying to rerun the migration I was getting Missing Defaults errors on a new table I was creating.
Since this is a brand new project I can just blow away the database and the migration scripts and try again. I would like to knwo what is potentially causing this missing migration.

You are missing the initialization of the fields.
So instead of author = models.CharField, use author = models.CharField(max_length=256) and also for all the others, use the parentheses.

Related

Making use of the users table, causing an error

In Django (2.x) I have an entry form, the model is here:
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
class Sample(models.Model):
sample_id = models.AutoField(primary_key=True)
area_easting = models.IntegerField()
area_northing = models.IntegerField()
context_number = models.IntegerField()
sample_number = models.IntegerField()
# taken_by = models.IntegerField()
taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.PROTECT)
def __str__(self):
return str(self.sample_id)
class Meta:
db_table = 'samples\".\"sample'
#ordering = ["sample_id"]
managed = False
#verbose_name_plural = "samples"
This works as expected, a list of usernames drops down (while I would like to format - firstname lastname). However, when I return to the main viewing page I see an error.
django.db.utils.ProgrammingError: column sample.taken_by_id does not exist
LINE 1: ...text_number", "samples"."sample"."sample_number", "samples"....
^
HINT: Perhaps you meant to reference the column "sample.taken_by".
Clearly Django is adding the _id to the table name causing the error, I expect because it is a foreign key.
Any ideas how to remedy this behaviour?
You can explicitly set the underlying db column via the db_column attribute:
taken_by = models.ForeignKey(settings.AUTH_USER_MODEL, db_column='taken_by', on_delete=models.PROTECT)
https://docs.djangoproject.com/en/2.1/ref/models/fields/#database-representation
^ link to the docs where it specifies that it creates a _id field.
based from the error message you have posted. It seems that your database schema is not updated.
you might need to do manage makemigrations and migrate to apply your model changes to your db schema
e.g
$ python manage.py makemigrations
# to apply the new migrations file
$ python manage.py migrate

Django queryset ProgrammingError: column does not exist

I'm facing a big issue with django.
I'm trying to save object containing foreignKeys and 'ManyToMany` but i always get this error
ProgrammingError: column [columnName] does not exist
I've made serveral times all migrations but it doesn't works. I have no problem when i work with models that does not contain foreign keys. I have tried to delete the migration folder. It's seems my database doesn't want to update fields. I need to force it to create these column but i don't have any idea.
class Post(models.Model):
post_id = models.CharField(max_length=100,default="")
title = models.CharField(max_length=100,default="")
content = models.TextField(default="")
author = models.ForeignKey(Users, default=None, on_delete=models.CASCADE)
comments = models.ManyToManyField(Replies)
numberComments = models.IntegerField(default=0)
date = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(null=True)
def __str__(self):
return self.post_id
when i'm trying to retrieve this i have :
ProgrammingError: column numberComments does not exist
As i said before i made makemigrations and migrate, i even deleted the migration folder.
Any idea ?
To save a instance of the POST model with foreign key you need to insert the query object.
Code example:
user = Users.objects.get(pk = 1)
p = POST(
title = 'Hello',
...
author = user,
date = '2018-01-01'
)
p.save()
You don't need to create post_id column, django creates one for you automatically, and you can access that using .pk or .id
You neither need numberComments. You should calculate that from comments many to many relation. Well... you can have this on DB too.
Next, you cannot add a many to many relation on creation. Create the post first as above. Then query the comment you want to add, the add the object to the relation
r = Replies.objects.get(pk = 1)
p.comments.add(r)
Hope it helps

Django: how to get related foreign key set?

I'm working in Django 1.8. I have models like this:
class School(models.Model):
code = models.CharField(primary_key=True)
name = models.CharField(max_length=200)
class Meta:
app_label = 'frontend'
class SchoolStatusOnDate(models.Model):
school = models.ForeignKey(School)
date = models.DateField()
setting = models.IntegerField()
I want to retrieve all the statuses associated with a particular school, and I think I should be able to do it using _set as described here, but it isn't working. This is my code:
s = School.objects.filter(code='A81018')
now = datetime.datetime.now()
SchoolStatusOnDate.objects.create(school=s, date=now, setting=4)
print s.schoolStatusOnDate_set.all()
But this gives me the following error on the final line:
AttributeError: 'School' object has no attribute 'schoolStatusOnDate_set'
What am I doing wrong?
schoolStatusOnDate_set should be lowercase.
From Django documentation: Following relationships “backward”:
If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased.
(emphasis mine)

Django migration error :you cannot alter to or from M2M fields, or add or remove through= on M2M fields

I'm trying to modify a M2M field to a ForeignKey field. The command validate shows me no issues and when I run syncdb :
ValueError: Cannot alter field xxx into yyy they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields)
So I can't make the migration.
class InstituteStaff(Person):
user = models.OneToOneField(User, blank=True, null=True)
investigation_area = models.ManyToManyField(InvestigationArea, blank=True,)
investigation_group = models.ManyToManyField(InvestigationGroup, blank=True)
council_group = models.ForeignKey(CouncilGroup, null=True, blank=True)
#profiles = models.ManyToManyField(Profiles, null = True, blank = True)
profiles = models.ForeignKey(Profiles, null = True, blank = True)
Any suggestions?
I stumbled upon this and although I didn't care about my data much, I still didn't want to delete the whole DB. So I opened the migration file and changed the AlterField() command to a RemoveField() and an AddField() command that worked well. I lost my data on the specific field, but nothing else.
I.e.
migrations.AlterField(
model_name='player',
name='teams',
field=models.ManyToManyField(related_name='players', through='players.TeamPlayer', to='players.Team'),
),
to
migrations.RemoveField(
model_name='player',
name='teams',
),
migrations.AddField(
model_name='player',
name='teams',
field=models.ManyToManyField(related_name='players', through='players.TeamPlayer', to='players.Team'),
),
NO DATA LOSS EXAMPLE
I would say: If machine cannot do something for us, then let's help it!
Because the problem that OP put here can have multiple mutations, I will try to explain how to struggle with that kind of problem in a simple way.
Let's assume we have a model (in the app called users) like this:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person)
def __str__(self):
return self.name
but after some while we need to add a date of a member join. So we want this:
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership') # <-- through model
def __str__(self):
return self.name
# and through Model itself
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
Now, normally you will hit the same problem as OP wrote. To solve it, follow these steps:
start from this point:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person)
def __str__(self):
return self.name
create through model and run python manage.py makemigrations (but don't put through property in the Group.members field yet):
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person) # <-- no through property yet!
def __str__(self):
return self.name
class Membership(models.Model): # <--- through model
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
create an empty migration using python manage.py makemigrations users --empty command and create conversion script in python (more about the python migrations here) which creates new relations (Membership) for an old field (Group.members). It could look like this:
# Generated by Django A.B on YYYY-MM-DD HH:MM
import datetime
from django.db import migrations
def create_through_relations(apps, schema_editor):
Group = apps.get_model('users', 'Group')
Membership = apps.get_model('users', 'Membership')
for group in Group.objects.all():
for member in group.members.all():
Membership(
person=member,
group=group,
date_joined=datetime.date.today()
).save()
class Migration(migrations.Migration):
dependencies = [
('myapp', '0005_create_models'),
]
operations = [
migrations.RunPython(create_through_relations, reverse_code=migrations.RunPython.noop),
]
remove members field in the Group model and run python manage.py makemigrations, so our Group will look like this:
class Group(models.Model):
name = models.CharField(max_length=128)
add members field the the Group model, but now with through property and run python manage.py makemigrations:
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
and that's it!
Now you need to change creation of members in a new way in your code - by through model. More about here.
You can also optionally tidy it up, by squashing these migrations.
Potential workarounds:
Create a new field with the ForeignKey relationship called profiles1 and DO NOT modify profiles. Make and run the migration. You might need a related_name parameter to prevent conflicts. Do a subsequent migration that drops the original field. Then do another migration that renames profiles1 back to profiles. Obviously, you won't have data in the new ForeignKey field.
Write a custom migration: https://docs.djangoproject.com/en/1.7/ref/migration-operations/
You might want to use makemigration and migration rather than syncdb.
Does your InstituteStaff have data that you want to retain?
If you're still developing the application, and don't need to preserve your existing data, you can get around this issue by doing the following:
Delete and re-create the db.
go to your project/app/migrations folder
Delete everything in that folder with the exception of the init.py file. Make sure you also delete the pycache dir.
Run syncdb, makemigrations, and migrate.
Another approach that worked for me:
Delete the existing M2M field and run migrations.
Add the FK field and run migrations again.
FK field added in this case has no relation to the previously used M2M field and hence should not create any problems.
This link helps you resolve all problems related to this
The one which worked for me is python3 backend/manage.py migrate --fake "app_name"
I literally had the same error for days and i had tried everything i saw here but still didn'y work.
This is what worked for me:
I deleted all the files in migrations folder exceps init.py
I also deleted my database in my case it was the preinstalled db.sqlite3
After this, i wrote my models from the scratch, although i didn't change anything but i did write it again.
Apply migrations then on the models and this time it worked and no errors.
This worked for Me as well
Delete last migrations
run command python manage.py migrate --fake <application name>
run command 'python manage.py makemigrations '
run command 'python manage.py migrate'
Hope this will solve your problem with deleting database/migrations
First delete the migrations in your app (the folders/ files under 'migrations'
folder)
Showing the 'migrations' folder
Then delete the 'db.sqlite3' file
Showing the 'db.sqlite3' file
And run python manage.py makemigrations name_of_app
Finally run python manage.py migrate
I had the same problem and found this How to Migrate a ‘through’ to a many to many relation in Django article which is really really helped me to solve this problem. Please have a look. I'll summarize his answer here,
There is three model and one(CollectionProduct) is going to connect as many-to-many relationship.
This is the final output,
class Product(models.Model):
pass
class Collection(models.Model):
products = models.ManyToManyField(
Product,
blank=True,
related_name="collections",
through="CollectionProduct",
through_fields=["collection", "product"],
)
class CollectionProduct(models.Model):
collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
class Meta:
db_table = "product_collection_products"
and here is the solution,
The solution
Take your app label (the package name, e.g. ‘product’) and your M2M field name, and combine them together with and underscore:
APPLABEL + _ + M2M TABLE NAME + _ + M2M FIELD NAME
For example in our case, it’s this:
product_collection_products
This is your M2M’s through database table name. Now you need to edit your M2M’s through model to this:
Also found another solution in In Django you cannot add or remove through= on M2M fields article which is going to edit migration files. I didn't try this, but have a look if you don't have any other solution.
this happens when adding 'through' attribute to an existing M2M field:
as M2M fields are by default handled by model they are defined in (if through is set).
although when through is set to new model the M2M field is handled by that new model, hence the error in alter
solutions:-
you can reset db or
remove those m2m fields and run migration as explained above then create them again
*IF YOU ARE IN THE INITIAL STAGES OF DEVELOPMENT AND CAN AFFORD TO LOOSE DATA :)
delete all the migration files except init.py
then apply the migrations.
python manage.py makemigrations
python manage.py migrate
this will create new tables.

How to access Foreign key models with custom primary key in django

These are my two models:
In models.py
class Person(models.Model):
person_no = models.IntegerField(max_length=10, primary_key='True')
phone = models.IntegerField(max_length=20)
class Meta:
db_table = 'person'
class person_ext(models.Model):
person_no = models.ForeignKey(Person)
key = models.CharField(max_length=64)
value = models.TextField()
class Meta:
db_table = 'personExt'
I went to manage.py shell to test my model and I tried to access the cell_phone of a person given the person's id this way:
p = Person.objects.get(pk=1)
cell_phone = Person_ext.objects.get(person_no=p).filter(key='cell').value
However, I'm getting the following error:
DatabaseError: (1054, "Unknown column 'personExt.person_no_id' in 'field list'")
My database column is just "person_id" but django is looking for "person_no_id". What do I have to do to access the personExt data using a person_no from person.
person_no_id is what I would expect for Django to look at. It appears that your database is actually out of sync with what your models expect. I would consider comparing the output of (sql)
SHOW CREATE TABLE `personExt `;
and
python manage.py sql APPNAME
for the table in question. You can fix this problem by using migration tools like south, recreating the database, or manually editing the database to fix the field. Alternatively you can change the model if you're importing:
person_no = models.ForeignKey(Person, db_column="person_id")
Edit: primary_key should be True, not the string "True," Indentation looks wrong for the Meta class and you should consider naming person_ext as PersonExt instead.