简体   繁体   English

没有主键我无法查询表

[英]I can't query a table without primary key

I'm trying to query through a model in Django that has no Primary Key . 我正在尝试通过Django中没有Primary Key的模型进行查询。 I need to query though it so I can access to the Foreign keys it has. 我需要查询它,以便可以访问它具有的Foreign keys

I'm just trying to do this atm and doesn't even work: 我只是在尝试执行此atm,甚至无法正常工作:

chars = Characterweapons.objects.all()

print(chars)

And if i change Characterweapons to Weapons for example, a table with Primary Key it works. 例如,如果我将Characterweapons更改为Weapons ,则具有主键的表将起作用。

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. 因此,看起来您在现有数据库上进行了DBinspect生成此模型。 I'm guessing this is failing because Django ORM expects your table to have a primary key. 我猜这是失败的,因为Django ORM希望您的表具有主键。 "id" is the default name for a Django generated model primary key field. “ id”是Django生成的模型主键字段的默认名称。 I suspect when you are trying to call Characterweapons.objects.all() it's trying to get the primary key field for some reason. 我怀疑当您尝试调用Characterweapons.objects.all() ,由于某种原因它试图获取主键字段。

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 Django文档中查看更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM