Django saying that table does not exist - python

I am new to Django and I am working in a project which is using a mysql DB.
They imported the DB to Django models and it seemed that it wasn't missing anything. When I did a query with Django, though, it was saying a table was missing. I checked the table name in the DB and it was matching. Pretty weird. I solved the problem anyway by using the syntax ".using('db_config').values('column1', 'column2')"
The model was the following:
class UserRoles(models.Model):
role_id = models.AutoField(primary_key=True)
class Meta:
managed = False
db_table = 'user_roles'
The command giving the error:
UserRoles.objects.filter(role_id=number)
The command without throwing the error:
r = UserRoles.objects.using('db_config').values('role_id')
q = r.filter(role_id=number)
The error was the following:
django.db.utils.OperationalError: no such table: user_roles
My question here is why did Django could not find the table before? Why did I need to use the method "values" to find the rows?? I checked and all the fields were matching.I also ran makemigrations, syncdb before
PS: Another odd thing that it was that the metatag "unique_together" didn't work as well. I had to use the method "values" to make the query work as well. I don't know if it s related somehow.

This has nothing to do with values, You're using the using method in the second query which is used to tell django which database you want to query.
Henceforth you're looking in a separate database which does have the relevant migrations applied

For anyone else who finds this when they Google it, the problem that I had that caused this same error (which was not the OP's problem, as it turns out) was that I had a router that assigned the model to different hosts for reading and writing, and the writing host was behind a firewall, so that would be another thing to check if you see that Django is saying the table does not exist when it definitely does.

Related

Django: managing permissions, groups and users during data migrations

Problem
During a data migration, I'm trying to create a django.contrib.auth.models.Group and some Users and then attaching said group to one of the users.
Problem I'm finding (other than the permissions still not being created, but I've already found a solution to that), is that for some reason the many-to-many manager doesn't seem to be working as it should (?).
Basically what I'm trying to do is something like:
group = Group.objects.create(name="manager")
# user creation...
user.groups.add(group)
However, I get the following error:
TypeError: Group instance expected, got <Group: manager>
Whenever I try to replicate this in the Django shell, it works without any problem. It only fails while doing migration. Any ideas?
Things I've tried and other information
I've tried both populating the m2m relation through the User related manager and the Group related manager, that is, user.groups.add(group) and group.user_set.add(user). Both give me a similar error.
Just partially related, but just so I have the permissions needed, I have this first in my migration:
for app_config in apps.get_app_configs():
app_config.models_module = True
create_permissions(app_config, verbosity=0)
app_config.models_module = None
The group is supposedly created properly. Given that I create the groups and the users in different helper functions, I actually grab the group with Group.objects.get(name="manager"), and when printing, it shows the correct information.
Turns out that the problem comes up when you use the django.contrib.auth.models.Group model directly. If instead you use apps.get_model("auth.Group"), everything works fine.

django table has no column named Exception

Git Repository
Request to guide me on what to do.
I work on an e-commerce website with the help of Django. and I'm a beginner in Django
The following image provides a table of my database. It helps to add a product
Shows me an error in the browser. This error shows me when I add a product inside the admin panel. It helps to add a product but when I add the product the following error occurs.
An error occurred while migrating
Request to guide me on what to do.
After first migrations,if you add any field that can not be null you must provide a default value. Your desc field is not nullable, so you must add default='some_value' inside your desc field.
Do you have the table ready and set up? Because the error says, that there is a table named shop_product, but it does not have a column named product_name.
So the structure of your table would get us closer to the solution of your problem.
Edit:
I have just seen, that you supplied your Git repo. I looked at the database and what I wrote above holds true. Your shop_product table has no columns. I did not look through your code to see if it would be set up automatically, but I suppose you were supposed to create the columns by hand, right?
Take a look at here (Django Migrations Workflow)
I've seen your migrations folder on your Github repo and there was no sign of any of the fields you mentioned.
Every time you add fields to your models, you need to run following commands in terminal
python manage.py makemigrations <app name>
python manage.py migrate
These commands are going to modify your tables.
Please markdown your question instead of putting a picture from your code.
Check this out: How do I ask a good question?
EDIT:
In your Product model, there is a field named desc. You need to set a default value for it; Otherwise, you need to update the records in your database manually.
desc = models.CharField(max_length=300, default='')
After you do that, this error will happen to the pub_date field too. So, if your current Product objects in your database are not important, you can simply delete the database file db.sqlite3 and delete your migrations file from this address shop/migrations/0001_initial.py and try the migration commands again.

Django incorrectly expecting id column

I'm working with an existing SQL database in Django. These tables for some reason were never given primary keys so I'm just going through and assigning them ones. In one of these models, I changed an existing unique index to a primary index using primary_key = True. I then ran ./manage.py makemigrations (app_name); ./manage.py migrate. I came across this error: (1091, "Can't DROP 'id'; check that column/key exists"). It seems as though Django assumed that there was an id field for the model when there wasn't because I was able to use phpMyAdmin to make an id field, and when I re-ran the migration it succeeded. While I was able to fix my problem I doubt that this is the best way to go about it. What is the correct way to deal with this problem?
You could fake a migration only including removing the "id" field using the --fake option when migrating, so django thinks that it had deleted the id field when really it never existed.

Django automatically create primary keys for existing database tables

I have an existing database that I'm trying to access with Django. I used python manage.py inspectdb to create the models for the database. Currently I'm able to import the models into the python shell however when I try to access any of the actual objects in any way, I get this error OperationalError: (1054, "Unknown column 'some_table.id' in 'field list'"). I see that the table in the database in fact does not have an id field. How can I fix this? Do I need to update the managed field in the Meta class and run a migration so it can create this field automatically?
From the Django documentation: This feature is meant as a shortcut, not as definitive model generation. See the documentation of inspectdb for more information. (Reference: https://docs.djangoproject.com/en/1.8/howto/legacy-databases/)
You're going to need to manually clean up the models and migrate. The line you'll have to add for adding the "id" field is:
id = models.IntegerField(primary_key=True)
Warning: I'd definitely create a copy of the database to toy with, rather than the original. This will likely take you some trial and error to get right. After you're absolutely sure you have it right, you can changed Managed=True, but be VERY careful!

members_data.dob may not be NULL in Django

Using Django 1.4 in my app I defined a model called Member and another called Data.Every member has basic like ID and it is related to a Data object that contains additional variables describing the "member".
I had initially created the member model without specifying that the dob variable could be NULL. I have since then changed this to allow for blank or null but I was still getting the members_data.dob may not be NULL error.
I thought it was because I needed to run a syncdb command, which I did, however this did not fix the problem.
dob = models.CharField(max_length=200, blank=True, null=True)
Any ideas? Thanks
ps. If you want to get an overall picture of what I am trying to implement please refer to: Can I use JSON data to add new objects in Django?
Thanks so much.
The syncdb command only creates tables if they do not exist. It does not handle migrations for you. You have a few options:
If there is no important data in the table, drop the table and run syncdb again to recreate it.
Update the column to allow null in a db shell. The correct command depends on which database you are using.
Use a migration tool, like South.
To drop the table in sqlite:
Open a dbshell
./manage.py dbshell
Drop the table
drop table <tablename>

Categories