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.
Related
Hi my code was running smoothly as i was following a tutorial but at a new step while adding new component in the model Order (processing, aprouved, refunbd_requested, refund_granted) the code crashed, the migrations operated but can't migrate i need help please.
my models.py
from django.conf import settings
from django.db import models
from django.shortcuts import reverse
from django_countries.fields import CountryField
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete= models.CASCADE)
items = models.ManyToManyField(OrderItem)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField()
ordered = models.BooleanField(default=False)
billing_address = models.ForeignKey('BillingAddress',
on_delete= models.SET_NULL, blank=True, null=True)
payment = models.ForeignKey('Payment',
on_delete= models.SET_NULL, blank=True, null=True)
coupon = models.ForeignKey('Coupon',
on_delete= models.SET_NULL, blank=True, null=True)
processing = models.BooleanField(default=False)
aprouved = models.BooleanField(default=False)
refund_requested = models.BooleanField(default=False)
refund_granted = models.BooleanField(default=False)
def __str__(self):
return self.user.username
def get_total(self):
total = 0
for order_item in self.items.all():
total += order_item.get_final_price()
if self.coupon:
total -= self.coupon.amount
return total
The last line of code for the error traceback after the migration, i try python manage.py migrate but i get that at the last line.
File "C:\Users\18094\AppData\Local\Programs\Python\Python37\lib\sitepackages\django\utils\dateparse.py", line 107, in parse_datetimematch = datetime_re.match(value)
The table might contain data that conflicts with the datatype, ie. one of your date fields.
Since this data is not critical, you can remove the data and start over.
assuming your app is named orders
./manage.py migrate orders zero # migrate to 0000, deleting the table
./manage.py migrate orders # migrate forward to current state
This method I am suggesting is a quick but not to recommend for the project in a production environment. You could try this out.
Make sure you add your app in the installed app, delete all your migrations folders, all the pycache folders, as well as the .sqlite file, then run the commands python manage.py makemigrations, python manage.py migrate and then start the server.
You could also run this python manage.py makemigrations app_name if the first command doesn't detect the migration
I hope this is helpful
I extend the Django user model like this:
#core.models
class Institute(models.Model):
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message=institute_phone_help_text)
name = models.CharField(_('name'), max_length=255)
description = models.TextField(_('description'), blank=True)
abbreviation = models.CharField(_('abbreviation'), blank=True, max_length=100)
address = models.TextField(_('address'), blank=True)
phone = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators should be a list
websites = ArrayField(models.URLField(max_length=255), verbose_name=_('websites'), blank=True, null=True)
class Meta:
verbose_name = _('institute')
verbose_name_plural = _('institutes')
def __str__(self):
return '{0} ({1})'.format(self.name, self.abbreviation)
class User(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
institute = models.ForeignKey(Institute, on_delete=models.CASCADE)
params = JSONField(_('params'), null=True, blank=True,)
about_me = models.TextField(_('about me'), blank=True,)
With an empty DB each time that I launch ./manage.py makemigrations core it creates always a new migration file
import django.contrib.auth.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20190430_1655'),
]
operations = [
migrations.AlterModelManagers(
name='user',
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]
I tried different combinations:
./manage.py makemigrations core
./manage.py migrate core
./manage.py migrate
./manage.py makemigrations core
./manage.py makemigrations core
./manage.py makemigrations
./manage.py migrate
It always creates the migration file.
Thanks.
D
if you use AbstractUser model make sure you run makemigrations before migrate.
i had same issue with AbstractUser,
I solved it by deleting the sqlite3 file also all migrations files.
After that i run this two commands :
python manage.py makemigrations
python manage.py migrate
inside your terminal
Let me know if that help!
Django 1.11 with PostgreSQL.
I go to migrate my site and models.py throws the error that I can't have more than one primary key. I can't see where I do (or I'm not understanding how).
class Employee(models.Model):
Aegis_ID = models.UUIDField(primary_key=True, null=False, default=uuid.uuid4, editable=False, serialize=True)
Employee_Number = models.ForeignKey('self', on_delete=models.CASCADE, related_name='Company_Employee_Number',
null=True, blank=True, max_length=6, help_text="Employee ID")
Employee_FName = models.CharField(null=True, blank=True, max_length=25, help_text="First Name")
Employee_LName = models.CharField(null=True, blank=True, max_length=25, help_text="Last Name")
Employee_Email = models.EmailField(max_length=80, blank=True, help_text="GPM Email address")
Employee_Position = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True,
related_name='Department_Employee_Position', max_length=3,
choices=EMPLOYEE_POSITION, help_text="Select position of this Employee.")
Hire_Date = models.DateField(null=True, blank=True, help_text="Enter the employee hire date.")
Employee_Division = models.CharField(max_length=2, null=True, blank=True, choices=DIVISION_CHOICES,
help_text="Assign the Audit Division for this employee.")
Employee_Region = models.CharField(max_length=3, null=True, blank=True, choices=REGION_CHOICES,
help_text="Assign the Audit Region for this employee.")
Employee_District = models.CharField(max_length=3, null=True, blank=True, choices=DISTRICT_CHOICES,
help_text="Assign the Audit District for this Employee.")
Reading the Django pages on this exact topic, it's listed as a problem resolved in 1.7 and had to do with how Django sorted the tables by class, alphabetically.
I've also tried python manage.py flush followed by makemigrations prior to migrate
So, what fields is Django / Postgres attempting to make an "id" and "primary" because I'm just not understanding, here...
According to the Django documentation regarding Automatic Primary Keys, there's the unseen is id = models.AutoField(primary_key=True) but I also understood that if you assign the primary_key=True to a field, this did not apply
In your above model Multiple primary keys for table “app_employee” are not allowed.
It is not coming because you have
Aegis_ID = models.UUIDField(primary_key=True, null=False, default=uuid.uuid4, editable=False, serialize=True)
Because in django documentation it is clearly specified that
Django Documentation
Field.primary_key
If True, this field is the primary key for the model.
If you don’t specify primary_key=True for any field in your model, Django will automatically add an AutoField to hold the primary key, so you don’t need to set primary_key=True on any of your fields unless you want to override the default primary-key behaviour.
primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object.
I have tried your model on my project and it is working absolutely fine.
For simplicity I removed other fields
models.py
from __future__ import unicode_literals
from django.db import models
import uuid
class Employee(models.Model):
Aegis_ID = models.UUIDField(primary_key=True, null=False,default=uuid.uuid4, editable=False, serialize=True)
Employee_Number = models.ForeignKey('self', on_delete=models.CASCADE, related_name='Company_Employee_Number',
null=True, blank=True, max_length=6, help_text="Employee ID")
Employee_FName = models.CharField(null=True, blank=True, max_length=25, help_text="First Name")
Employee_LName = models.CharField(null=True, blank=True, max_length=25, help_text="Last Name")
Employee_Email = models.EmailField(max_length=80, blank=True, help_text="GPM Email address")
and when I did
(venv) astikanand#Developer-PC:~/firstsite$ python manage.py makemigrations
Migrations for 'employee':
employee/migrations/0001_initial.py
- Create model Employee
and then
(venv) astikanand#Developer-PC:~/firstsite$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, employee, sessions
Running migrations:
Applying employee.0001_initial... OK
so it is working fine.
You need to do is
Either you recreate your app or simply start your project all over again, may be some dependency issues or something. But your code for model Employee is all ok.
It is quiet possible that you changed primary keys and/or references to other models/tables and some legacy dependencies remained in the migration files.
Please refer to the official Django documentation for reverting past migrations. You do not have to restart your project to remove dependencies.
python manage.py makemigrations --empty yourappname
That is it. Then check 0001_initial.py file under migrations folder in your app to make sure all dependencies have been removed. It should look like:
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('yourappname', '0001_initial'),
]
operations = [
]
Im working on a Django project using south for schema migrations.
I have the following scenario:
schema
class Book(model.Models):
name = models.CharField(max_length=255, blank=True)
bid = models.IntegerField(blank=True, null=True)
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
book_id = models.ForeignKey(Book, null=True, to_field="bid", db_column="bookID")
I wanna change Author model to the following:
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
book = models.ForeignKey(Book, null=True, db_column="book_id")
but without loose data. I want to search each book by its bid and assign the one found to the new field in Author model.
Thanks
You'll have to do a 3 migrations. A schemamgiration that adds the new book FK, then a data migration and then a schemamigration to delete and rename the fields.
So you'll want to change your models.py file to this:
class Book(model.Models):
name = models.CharField(max_length=255, blank=True)
bid = models.IntegerField(blank=True, null=True)
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
book_id = models.ForeignKey(Book, null=True, to_field="bid", db_column="bookID")
# You don't need the db_column="book_id" since that's what it does at the DB level by default.
# I'm not sure if things will break if you name it book with another field as book_id.
book_new = models.ForeignKey(Book, null=True)
Then run python manage.py schemamigration APP_NAME auto
Then run ```python manage.py datamigration APP_NAME populate_book_id
Then edit the newly created data migration and loop through the Author instances setting the new book field with the book_id field. Don't forget to remove the book field values in the backwards method.
Then change your models.py file to the following:
class Book(model.Models):
name = models.CharField(max_length=255, blank=True)
bid = models.IntegerField(blank=True, null=True)
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
# You don't need the db_column="book_id" since that's what it does at the DB level by default.
book = models.ForeignKey(Book, null=True)
Then run python manage.py schemamigration APP_NAME auto
You'll want to check this last schemamigration to make sure it's renaming book_new to book and not dropping and creating columns. Here's an answer that explains how to change it.
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?