I'm trying to read values from an sqlite db I added to my Django project but it doesn't work.
I did a test in the Python shell and all it returned was the following error when I tried looking into the data:
from myapp.models import my_data
my_data.objects.all()
OperationalError: no such column: my_table_name.id
This is how my models.py file looks like:
class my_data(models.Model):
status = models.TextField(db_column='STATUS', blank=True, null=True)
name_1 = models.TextField(db_column='NAME_1', blank=True, null=True)
name_2 = models.TextField(db_column='NAME_2', blank=True, null=True)
dep = models.IntegerField(db_column='DEP', blank=True, null=True)
name_reg = models.TextField(db_column='NAME_REG', blank=True, null=True)
reg = models.IntegerField(db_column='REG', blank=True, null=True)
name_com = models.TextField(db_column='NAME_COM', blank=True, null=True)
avgp = models.IntegerField(db_column='AVGP', blank=True, null=True)
class Meta:
managed = True
db_table = 'my_table_name'
My settings.py file:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'my_table_name': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db_my_table_name.sqlite3'),
}
}
Also, I performed the python manage.py makemigrations and python manage.py migrate commands.
Any idea what I am doing wrong?
I write this according to this comment since you said it worked:
Add a id field to my_data model:
AutoField like: id = models.AutoField(primary_key=True)
Tip: In django model names should follow CamelCase convention.
I had the same issue before then i used the below code for my models.py file, this has resolved the issue
class ModelName(models.Model):
id = models.AutoField(primary_key=True)
This could help you to resolve the above Problem
Add this in your models.py:
id = models.AutoField(primary_key=True)
Related
I am getting the error Model instances without primary key value are unhashable when trying to remove a model instance from my admin panel.
models.py
from djongo import models
import uuid
PROPERTY_CLASSES = (
("p1", "Video Property"),
("p2", "Page Property"),
("trait", "Context Trait"),
("custom", "Custom Property")
)
EVENT_TYPES = (
("video", "Video Event"),
("track", "Track Event"),
("page", "Page Event")
)
class Device(models.Model):
_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255)
class Platform(models.Model):
_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255)
app_name_possibilities = models.TextField(blank=True)
class EventPlatformDevice(models.Model):
_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = ""
event_field = models.ForeignKey('Event', on_delete=models.CASCADE)
applicable_apps = models.ManyToManyField('Platform', blank=True)
applicable_devices = models.ManyToManyField('Device', blank=True)
property_group = models.ManyToManyField('PropertyGroup', blank=True)
custom_properties = models.ManyToManyField('Property', blank=True)
class Event(models.Model):
_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255, unique=True)
event_type = models.CharField(max_length=20, choices=EVENT_TYPES)
class PropertyGroup(models.Model):
_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100)
applicable_properties = models.ManyToManyField('Property')
class Property(models.Model):
_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255)
property_class = models.CharField(max_length=20, choices=PROPERTY_CLASSES)
format_example = models.TextField(blank=True)
notes = models.TextField(blank=True)
The issue lies with the EventPlatformDevice model I believe. The issue I think is when I create a new entry in the Admin panel and setup the relationships between EventPlatformDevice.applicable_apps it gets saved into the MongoDB using a _id:ObjectId("61c25d36cdca07c8a6101044") since that is what Mongo uses. I changed all of my primary keys to use a UUID since that was the only way I could get it to work. Now I think it is having a issue that some of my items are using ObjectId while some are using the _id:Binary('7w6NaYCQQn6BS7jaOXUNZw==', 3) that I am getting from uuid.
Is it possible to define what type the _id field is for everything? That way I can set it to use UUID.
Attached are images showing the data in Compass.
When I did not specify the _id in all my models, I was getting errors when deleting and accessing. It was like Django did not know how to reference the ObjectId. That is why I went with UUID. But since I cannot control the dd.parsers_eventplatformdevice_applicable_apps (2nd pic) it is having issues deleting it.
Is it possible to define what type the _id field is for everything?
I am afraid not. Each driver implementations may implement UUID serialization and deserialization logic differently, which may not be fully compatible with other drivers. (docs).
First, You can configure a UUID Representation, since PyMongo is using a legacy method to encode and decode UUID (0x03 subtype), you can change to cross-language compatible Binary 0x04 subtype. To do so in Djongo, just provide uuidRepresentation in the database settings as a standard (docs):
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'dd',
'ENFORCE_SCHEMA': False,
'CLIENT': {
'host': 'mongodb://localhost:27017',
'uuidRepresentation': 'standard',
'waitQueueTimeoutMS': 30000
},
},
}
Second, I would definitely try to make _id works. So the cration of the _id field will be provided by MongoDB server.
If that does not work for you:
_id = models.ObjectIdField(primary_key=True)
then you could try this one:
_id = models.AutoField(auto_created=True, primary_key=True, unique=True)
So, I am actively trying to create categories with subcategories. My current app is listings, and the idea is to create a ManyToManyField inside my Listing models. Here is my code inside models.py.
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
class Category(MPTTModel):
name = models.CharField(max_length=150, unique=True)
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by = ['name']
class Blist(models.Model):
name = models.CharField('Business Name', max_length=250)
address = models.CharField('Address', max_length=300)
city = models.CharField('City', max_length=100)
zip_code = models.CharField('Zip Code', max_length=10)
phone_number = models.CharField('Phone Number', max_length=20)
web = models.URLField('Website')
def __str__(self):
return self.name
But when I go into the shell to add items into the category, I'm getting errors:
django.db.utils.ProgrammingError: column listings_category.name does not exist
LINE 1: SELECT "listings_category"."id", "listings_category"."name",...
Once finished, I ran makemigrations and migrate, but I realize it is not creating the tables in my database. I'm using Postgresql.
What am I doing wrong here?
I have written a custom django migrations command as shown below
User = get_user_model()
def populate_asset_assignee(apps, schema_editor):
for user in User.objects.all():
user.save()
# Some more code
The user model looks as follows
class User(AbstractUser):
username = None
email = models.EmailField(max_length=50, unique=True)
cohort = models.IntegerField(blank=True, null=True)
slack_handle = models.CharField(max_length=50,
blank=True, null=True)
picture = models.CharField(max_length=255, blank=True, null=True)
phone_number = models.CharField(max_length=50, blank=True, null=True)
last_modified = models.DateTimeField(auto_now=True, editable=False)
password = models.CharField(max_length=128, blank=True, null=True)
location = models.ForeignKey('SomeCentre',
blank=False,
null=True,
on_delete=models.PROTECT)
# Some more fields
I added the location field recently and have the migrations for it which is applied after this custom migration has been applied. The problem I am having is that whenever I try to make the migrations on the test db or a new database, I get the error django.db.utils.ProgrammingError: column core_user.location_id does not exist which is being raised inside the populate_asset_assignee method when I try to do the user in User.objects.all()
Any ideas why location_id is beeing checked yet I haven't applied the migrations for the location field yet.
I have a model called "news", defined below:
class News(models.Model):
title = models.CharField(max_length=30, null=False, blank=False, verbose_name="news title")
content = models.TextField(max_length=300, null=False, blank=False, verbose_name="news content")
cta = models.CharField(max_length=50, null=False, blank=False, verbose_name="news call-to-action")
mini_image = models.URLField(null=False, blank=False, verbose_name="news image helper")
is_promo = models.BooleanField(null=False, blank=False, verbose_name="promo code")
promo_benefit = models.DecimalField(max_digits=7, decimal_places=2, blank=False, null=False, default=0.00, verbose_name="promo benefit")
promo_duration = models.IntegerField(null=False, blank=False, default=0, verbose_name="promo duration")
date_published = models.DateTimeField(auto_now_add=True, null=False, blank=False)
def __str__(self):
return self.title
And when I try to access a template that uses the news model (whether I'm logged into admin trying to create a new instance or on a custom template), I get the following error:
ProgrammingError at /admin/myapp/news/
column omninectar_news.cta does not exist
LINE 1: ...app_news"."title", "myapp_news"."content", "myapp...
^
Any ideas on how I can fix this issue?
column omninectar_news.cta does not exist
That should be self-explanatory. Your database is out of date.
If you use South, migrate. Otherwise, try to remove the table "omnictar_news" and then run syncdb.
You should to delete the migrations folder and then
python manage.py migrate --run-syncdb
python manage.py migrate --fake appname
I am working allong with Django book. Now I'm on the fifth chapter(Models) and right now I'm dealing with some problems. For instance, when I'm trying to write in my shell: python.py manage.py sqlall my_app_name I am getting this message:
Where is my mistake?
P.S. My my_app.models.py:
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
My project settings.py databases configuration:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'mydb',
'USER': 'admin', # Not used with sqlite3.
'PASSWORD': '123', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used wit
}
}
And finally - my project settings.py INSTALLED_APPS and MIDDLEWARE_CLASSES:
INSTALLED_APPS = (
#'django.contrib.admin',
#'django.contrib.auth',
#'django.contrib.contenttypes',
#'django.contrib.sessions',
#'django.contrib.messages',
#'django.contrib.staticfiles',
'books', # MY APP NAME
)
MIDDLEWARE_CLASSES = (
#'django.contrib.sessions.middleware.SessionMiddleware',
#'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
#'django.contrib.auth.middleware.AuthenticationMiddleware',
#'django.contrib.messages.middleware.MessageMiddleware',
#'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
If you need any more information just say. Thank you in advance!
The error message is quite explicit that this is a problem with connecting to the database with that username and password. Have you set that account up in Postgres?