I'm trying to query through a model in Django that has no Primary Key.
I need to query though it so I can access to the Foreign keys it has.
I'm just trying to do this atm and doesn't even work:
chars = Characterweapons.objects.all()
print(chars)
And if i change Characterweapons to Weapons for example, a table with Primary Key it works.
The error I get when I load the page is this:
Exception Value: (1054, "Unknown column 'characterweapons.id' in 'field list'")
This is my model:
class Characterweapons(models.Model):
characterid = models.ForeignKey(Characters, models.DO_NOTHING, db_column='CharacterID') # Field name made lowercase.
weaponid = models.ForeignKey(Weapons, models.DO_NOTHING, db_column='WeaponID', blank=True, null=True) # Field name made lowercase.
categoryid = models.ForeignKey(Category, models.DO_NOTHING, db_column='CategoryID', blank=True, null=True) # Field name made lowercase.
quantity = models.IntegerField(db_column='Quantity', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'characterweapons'
def __str__(self):
return '%s %s %s %s' % (self.quantity,self.characterid,self.weaponid,self.categoryid)
Anyone knows about this?
Thanks in advance!
So it looks like you did a DBinspect on an existing database to generate this model. I'm guessing this is failing because Django ORM expects your table to have a primary key. "id" is the default name for a Django generated model primary key field. I suspect when you are trying to call Characterweapons.objects.all() it's trying to get the primary key field for some reason.
There may be a workaround but unless you really know what your doing with your database, I would highly urge you to set a primary key on your tables.
The best solution that I found, in this case, was to perform my own query, for example:
fact = MyModelWithoutPK.objects.raw("SELECT * FROM my_model_without_pk WHERE my_search=some_search")
This way you don't have to implement or add another middleware.
see more at Django docs
Related
i have an error in my django admin:
(1054, "Unknown column 'flora2estado.id' in 'field list'")
the model flora2estado has two fields, they are used in unique together as a pseudo composite key, how can i fix this?
admin.py
admin.site.register(Flora2Estado)
models.py
estado = models.OneToOneField(Estados, models.DO_NOTHING, primary_key=True)
especie_id = models.IntegerField()
flora2estado = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'flora2estado'
unique_together = (('estado', 'especie_id'),)
I tried to add the "flora2estado" field without sucess.
All migrations done, thank you for your time
Django is trying to select id field, as documented
By default, Django gives each model the following field:
id = models.AutoField(primary_key=True)
If you’d like to specify a custom primary key, specify
primary_key=True on one of your fields. If Django sees you’ve
explicitly set Field.primary_key, it won’t add the automatic id
column.
I have a webservice setup with Django backend and I am trying to delete entries for my Field objects. Each Field is assigned to a User and there are a number of Assessments done in the Field. The Assessments are linked to the Fields via a foreign key. Upon deletion of the Field object I want to also delete all the Assessments for that Field, but keep the User.
I played around with the on_deletion parameter and if I set it to CASCADE the Django admin page shows me all the associated Assessment objects if I try to delete the Field object. However, I am still getting the following error:
IntegrityError at /admin/dfto/field/ update or delete on table "field"
violates foreign key constraint "assessment_field_uuid_fkey" on table
"assessment" DETAIL: Key
(uuid)=(f3a52c10-33be-42f9-995d-482025cea17b) is still referenced from
table "assessment".
These are my models for Reference:
class Assessment(models.Model):
uuid = models.TextField(primary_key=True)
longitude = models.FloatField(blank=True, null=True)
latitude = models.FloatField(blank=True, null=True)
field_uuid = models.ForeignKey('Field', models.CASCADE, db_column='field_uuid',blank=True, null=True, related_name='assessments')
class Meta:
db_table = 'assessment'
class Field(models.Model):
uuid = models.TextField(primary_key=True)
name = models.CharField(max_length=50, blank=True, null=True)
country = models.CharField(max_length=50, blank=True, null=True)
user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email')
crop_uuid = models.ForeignKey(Crop, models.CASCADE, db_column='crop_uuid')
class Meta:
db_table = 'field'
Can someone explain to me why I am getting this error and/or provide a fix for me?
I think it's because field_uuid have argument 'models.CASCADE' so when you are deleting it, django also tries to delete any refences to this particular key, don't know how to fix it tho.
I am developing a web app using Django. I have created the table in MySQL database and then generated the models.py using inspectdb. I am able to fetch details and connect to the database without any issues. But while saving the values to the particular table, below error is shown
sav_list = List(id=4, item_name ='name1', item_desc='desc1', location='location', reason='rfp', pid=3)
Cannot assign "3": "List.id" must be a "Order" instance.
my models
class List(models.Model):
id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
item_name = models.CharField(db_column='Item_Name', max_length=255) # Field name made lowercase.
item_desc = models.CharField(db_column='Item_Desc', max_length=300) # Field name made lowercase.
location = models.CharField(db_column='Location', max_length=100, blank=True, null=True) # Field name made lowercase.
reason = models.CharField(db_column='Reason', max_length=100, blank=True, null=True) # Field name made lowercase.
pid = models.ForeignKey('Order', models.DO_NOTHING, db_column='PID') # Field name made lowercase.
class Order(models.Model):
poid = models.IntegerField(db_column='POID', primary_key=True) # Field name made lowercase.
po = models.CharField(db_column='PO', unique=True, max_length=20) # Field name made lowercase.
quote = models.CharField(db_column='Quote', unique=True, max_length=20) # Field name made lowercase.
condition = models.CharField(db_column='Condition', max_length=15) # Field name made lowercase.
I have tried relate_name for foreign key but still same behaviour. Same values can be stored on database without any issues. Only Django throws an error.
Please someone help me!!!
You should paste the actual error; it is presumably that "List.pid" must be an "Order" instance.
The error should be clear. pid is a ForeignKey field, it expects an instance of the related model. You can either get the item and set it:
pid = Order.objects.get(pk=3)
List(...., pid=pid)
or use the underlying id field:
List(...., pid_id=3)
The pid column at the Django level is not an id (integer), yes on the database level it is. But in Django it is a foreign key, and thus it refers to an Order instance. You thus should pass it an Order instance (the one that corresponds to poid=3).
But we are lucky, in case you construct such ForeignKey, Django automatically makes a field_id column that stores the id, and those two fields act like twins. We can thus assign 3 to pid_id:
sav_list = List(
id=4,
item_name ='name1',
item_desc='desc1',
location='location', reason='rfp',
pid_id=3
)
Note however that for most database backend, foreign key constraints will check if there is an Order instance with as referenced column (in Django the primary key) 3 exists. If not, it is impossible to create such List. I would therefore advice to ensure that such Order exists before trying to save it to the database.
The Model class are generated by the django inspectdb and i can see the Id field, this is converted from the Legacy tables, the table cant be altered here,
class workFlowTemplate(models.Model):
rev = models.IntegerField(null=True, blank=True)
revtype = models.IntegerField(null=True, blank=True)
**id = models.IntegerField(null=True, blank=True)**
name = models.CharField(max_length=255, blank=True,primary_key=False)
class Meta:
db_table = 'workflow_template'
the problem is when i try to run the django it throws error
CommandError: One or more models did not validate:
pHApp.workflowtemplate: "id": You can't use "id" as a field name, because each model automatically gets an "id" field if none of the fields have primary_key=True. You need to either remove/rename your "id" field or add primary_key=True to a field.
Note
the id is not primary key here in this case,
When i tries to change
id = models.IntegerField(null=True, blank=True,primary_key=False)
the Issue still remains the same, and same error is repeated again, how to avoid this Issue ?
A model must have a primary key, so you need specify a primary key field, like this:
my_primary_key = models.AutoField(primary_key=True)
id = models.IntegerField(null=True, blank=True)
then it won’t add the automatic id column and you will not receive this error.
Column id is adding by django by default, if you did not specified another field as PK.
In your case, you specified id as your field, but you did not specified what field should be a primary key.
Solution - set another field as primary key since you can not rename id
Regardless of what I do, I cannot seem to lose this error in a django model:
Did you rename twitterbot.bot to twitterbot.userbot (a ForeignKey)? [y/N] y
You are trying to add a non-nullable field 'twitbot_id' to twitterbot without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows)
2) Quit, and let me add a default in models.py
Select an option: 2
As you can see here, I've set it up properly according to documentation, giving an "autofield".
So what is causing this error to persist? Creating Null = True / False seems to change nothing.
class TwitterBot(models.Model):
twitbot_id = models.AutoField(primary_key=True)
userbot = models.ForeignKey(UserBot)
user_id = models.CharField(max_length=90, blank=True, null=True)
screenname = models.CharField(max_length=200, blank=True, null=True)
oauth_token = models.CharField(max_length=90, blank=True, null=True)
oauth_token_secret = models.CharField(max_length=90, blank=True, null=True)
hashtags = models.CharField(max_length=200, blank=True, null=True)
Django adds a default "id" field to every model, you don't need an extra "twitbot_id" in your model. If a surrogate primary key is all you need, forget about "twitbot_id" because it will be a duplicate of the auto-generated "id". See https://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields
If you add this and you already have TwitterBot objects in your database you must provide a default value to populate this column for existing rows in the database.