This is a follow-up / clarification to this question.
I'm using Django 2.1, Python 3.6, and Oracle 12c.
Suppose I have two models:
class ModelA(models.Model):
modelB_field = ForeignKey(ModelB, on_delete=models.DO_NOTHING)
example_field = models.IntegerField()
class ModelB(models.Model):
example_field = models.IntegerField()
Then if I do
ModelA.objects.filter(...).select_related('modelB_field')
I get
django.db.utils.DatabaseError: ORA-00918: column ambiguously defined
Three observations:
I only get the error if the field example_field is in both
models...even though it is not the primary key of ModelB.
The query that Django generates works in sqldeveloper.
The code works if I use a virtualenv with Django 2.0 instead of Django
The docs don't indicate anything changed with select_related in Django 2.1.
Definitely, its a bug on django 2.1, try downgrading to 2.0...
Related
Let's suppose I have the following model:
class Test(models.Model):
field_one = models.CharField(max_length=80)
Now, we have created 2-3 Model objects with field_one field.
p1 = Test(field_one="Object1")
p1.save()
p2 = Test(field_one="Object2")
p2.save()
Later, I realised that I need to add another field field_two to my Test model.
class Test(models.Model):
field_one = models.CharField(max_length=80)
field_two = models.IntegerField(default=3)
Now, Doing makemigrations & migrate
and running server.
which will prompt the following error
django.db.utils.ProgrammingError: column mainapp_test.field_two does not exist
I understand that this error occurs due to my 2 existing objects in PostGresDB doesn't have field_two column.
Is there any effective way to add field_two column to my existing objects with some default value? or How to solve this problem?
Django Version: 2.0
Django ORM DB: PostGresql
When you add a field to an existing model, you must either provide a default value in the code, or set it to null/blank = True, or provide a one-off default while migrating.
Since you are providing a default in the code, the migration should run without issues. At least from experience, I've added several BooleanFields with default=False to my existing model with thousands of entries, and I never got a ProgrammingError.
Have you tried shutting down the Postgres backend before running makemigrations and migrate? I would think Django would do this but that's the only thing I can think of. Also, obviously, shut down the Django server if it's still running.
I have the following model at Django:
class Community(models.Model):
name = models.CharField(max_length=255)
members = models.ManyToManyField(User, through='Membership')
date_created = models.DateTimeField(auto_now_add=True)
But when I check the structure of the table (using Postico for PostgreSQL) the field of date_created after applying the migrations shows no default.
I have also tried with explicitly default=date.today() but it does not work.
Any ideas what I am missing?
Thanks,
Pablo
EDIT
Great thanks to this post: How to make a script to insert data in my default sqlite3 database django
I was trying to populate the database via script using PostgreSQL driver, when it is way simpler importing the Django models a use the create method (also thanks to Daniel Roseman in the comments that led me find the post).
I am not a coder by any means but I have to do a project for college and I am really stuck, any help would be greatly appreciated.
I am using Django and SQLite. I want to join the auth_user table with an input table that I created. I have run the following SQL join which has given me the result I want.(Which is that every user has there own waist measurement) But my issue is I don't know how to implement this into Django?
This is my SQL statement:
Sql
Please Help!
Django has its own ORM (Making queries | Django docs). So that you specify the table structure with the models. I'll give you an example
models.py
from django.db import models
class AuthUser(models.Model):
first_name = models.CharField(
max_lenth=250
)
class ProjectInput(models.Model):
auth_user = models.ForeignKey(to='AuthUser', on_delete=models.CASCADE)
waist = models.PositiveIntegerField()
so you create AuthUser model and ProjectInput model and you have foreign key relation between them (Models | Django docs).
so with this models you can create the query in Django ORM like
full_name_waist = ProjectInput.objects.values_list('auth_user__full_name', 'waist')
these are the very basics od Django. I suggest you reading tutorials in the django - Getting Started | Django docs.
more sources:
Django ORM - Full Stack Python
Filtering on Django GenericRelations has been implemented 4 years ago via https://code.djangoproject.com/ticket/22207 and supports now to filter from the related model:
class Issue(models.Model):
project_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=False, null=True)
project_id = models.PositiveIntegerField(blank=False, null=True)
project = GenericForeignKey('project_content_type', 'project_id')
class GitlabProject(models.Model):
issues = GenericRelation(
Issue,
related_query_name='generic_project',
content_type_field='project_content_type',
object_id_field='project_id',
)
and then:
issues = queryset.filter(generic_project__offers__members__in=[request.user])
We cannot use just project__offers_members - it would fail, as Django does not reversely resolve Generic Foreign Keys.
However what happens if we have another project model with the same related_query_name?
class JiraProject(models.Model):
issues = GenericRelation(
Issue,
related_query_name='generic_project',
content_type_field='project_content_type',
object_id_field='project_id',
)
I have tried setting the GenericRelation with the same related_query_name on all the different project models (i.e. Gitlab Project, Jira Project, etc.). However that results in Django picking up only the 'first' project model. The generic relation to all subsequent project models are ignored and as a result, issues that have instances set that do not belong to the 'first' project model are ignored and not part of the queryset.
I think Django should either support this or issue a warning or error (possibly when executing the makemigrations command), when multiple GenericRelations have the same related_query_name value set.
How can one filter efficiently across issues that have their project attribute set to instances of different models?
edit: I wasn't clear before, I am saving my object in the django admin panel, not in a view. Even when I save the object with no many-to-many relationships I still get the error.
I have a model called TogglDetails that has a ForeignKey relationship with the standard django User model and a MayToManyField relationship with a model named Tag. I have registered my models with django admin but when I try to save a TogglDetails instance I get the error in the title.
Here are my models:
class Tag(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class TogglDetails(models.Model):
token = models.CharField(max_length=100)
user = models.ForeignKey(User)
tags = models.ManyToManyField(Tag, blank=True, null=True)
def __unicode__(self):
return self.user.username
class Meta:
verbose_name_plural = "toggl details"
As far as I can tell, there should be no issues with my models and django admin should just save the instance without any issues. Is there something obvious that I have missed?
I am using Django 1.3
The answer to my question was this: Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3
The sequences in my postgres database did not have the "Owned by" attribute set and so did not return an id when a new entry was saved to the db.
As stated by other users:
Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3
The sequences in my postgres database did not have the "Owned by" attribute set and so did not return an id when a new entry was saved to the db
In addition:
This is most likely caused by a backwards incompatible change that renders some primary key types in custom models beyond reach for Django 1.3. See Django trac tickets https://code.djangoproject.com/ticket/13295 and http://code.djangoproject.com/ticket/15682 for more information.
I solved the problem by running the follow commands for the affected tables/sequences.
Specifically running the command:
manage.py dbshell
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
change tablename_colname_seq and tablename.colname
Don't let us guess and add the Error message to your question, this gives most information about where it fails.
Have you imported the User model?
from django.contrib.auth.models import User
I've had this problem as well and the only thing I could do was make the M2M fields blank and not set them until I hit Save and Continue Editing.
I think this just may be a framework wart, as you will notice the User section of the Admin site also has a very strict "You can only edit these fields until you save the model".
So my recommendation is to adopt that scheme, and hide the M2M form field until the model has a Primary Key.
I tried Django 1.3 using CPython, with different database setups. I copy-pasted the models from the question, and did some changes: first I added
from django.contrib.auth.models import User
at the top of the file and I put the reference to Tag between quotes. That shouldn't make any difference. Further, I created the following admin.py:
from django.contrib import admin
import models
admin.site.register(models.Tag)
admin.site.register(models.TogglDetails)
For Sqlite3, the problem described doesn't occur, neither for MySQL. So I tried PostgreSQL, with the postgresql_psycopg2 back end. Same thing: I can't reproduce the error.
So as far as I can figure, there's nothing wrong with the code in the question. The problem must be elsewhere.