I'm using model like this:
class Product(models.Model):
name = models.CharField(max_length=100)
group = models.ForeignKey(Category.objects.filter(group__category__name='foo'))
issue is getting error django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
You should pass model as ForeignKey argument not a queryset.
If you need to restrcit foreign key choices try to use limit_choices_to:
group = models.ForeignKey(Category, limit_choices_to={'name'='foo'})
Related
I have a database view that relates 2 companies by foreign keys like so:
DB company_view:
company1_id FK to Company,
company2_id FK to Company,
description text
where
--- some company criteria ---
I try model in Django as unmanaged like so:
class CompanyView(models.Model):
company1 = models.ForeignKey(Company, related_name='company1_id', parent_link=True)
company2 = models.ForeignKey(Company, related_name='company2_id', parent_link=True)
description = models.TextField()
class Meta:
managed = False
db_table = 'company_view'
For the Admin class I have:
#admin.register(models.CompanyView)
class CompanyViewAdmin(AdvancedModelAdmin):
list_display = ('company1', 'company2', 'description')
But the admin page throws exception like:
psycopg2.errors.UndefinedColumn: column company_view.id does not exist
It doesn't make sense to have a primary id key, so is there any way around this?
Thanks
why you dont make a many-to-many relationship?
company = models.ManyToManyField(Company)
look: https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/
this will solve your problem, since it use a object instance.
im creating 2 models in django, the first one has django auth user as a foreign key, the second has this first model as a foreign key like this in models.py :
class SGIUsers(models.Model):
charge = models.CharField('Cargo', max_length=80)
user = models.ForeignKey(User, unique=True)
class ResponsibleStateFlow(ModelBase):
user = models.ForeignKey(SGIUsers, verbose_name = 'Responsable', blank = False )
process= models.ForeignKey(Process, verbose_name='Proceso')
But i get this error :
sgiprocess.ResponsibleStateFlow.user: (fields.E300) Field defines a relation with model 'SGIUsers', which is either not installed, or is abstract.
I already imported django auth user of course. Any idea ??
try to add the app name:
field=models.ForeignKey('app_name.ModelName')
Found it, i needed to define an app label with the app name in class meta for SGIUsers like this first:
class Meta:
app_label = 'app_name'
And then call the foreign with 'app_name.Modelname'
I have found in internet different examples on how to handle m2m relations with existing DB models, such as ex1 or here ex2, however I'm still not able to solve the error I get.
My models are depicted below. Basically, all the tables where created manually.
I got the following error message:
OperationalError: (1054, "Unknown column 'supervisor_project.id' in 'field list'").
I'm still a bit confused on when to use unique_together with through. Do you see any errors in the model below? The table supervisor_project has no id field and its PK is composed actually of two FK's, i.e. surrogate PK.
class Supervisor(models.Model):
name = models.CharField(max_length=45, blank=True, null=True, help_text="Name, e.g. John Smith")
class Meta:
managed = False
db_table = 'supervisor'
def __unicode__(self):
return self.name
class Project(models.Model):
title = models.CharField(max_length=45, blank=True, null=True)
supervisors = models.ManyToManyField(Supervisor, through='SupervisorProject', through_fields=('project', 'supervisor'))
class SupervisorProject(models.Model):
supervisor = models.ForeignKey('Supervisor', on_delete=models.CASCADE)
project = models.ForeignKey('Project', on_delete=models.CASCADE)
class Meta:
managed = False
db_table = 'supervisor_project'
unique_together = (('supervisor', 'project'),)
Django requires each model to have exactly one primary key field. It doesn't support multiple-column primary keys yet.
Since you haven't explicitly defined a primary key on the SupervisorProject model, Django assumes that there is an automatic primary key field id. When it includes the id field in a query, you get the error because it doesn't exist.
If possible, I would add an auto-incrementing id column to each intermediate table. There isn't a way to get Django to add the column to the tables automatically. You have set managed=False, so Django expects you to manage the database table.
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)
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.