Django:查询不带主键的只读视图 [英] Django: Querying read-only view with no primary key

查看:795
本文介绍了Django:查询不带主键的只读视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



$ Meta:
db_table ='read_only_view'

def main(request):
result = dbview.objects.all()

在呈现时捕获异常:(1054,未知列read_only_view。域列表中的 id



no primary key 我可以在视图中看到。有没有解决方法?



评论:

我无法控制我正在使用Django访问的视图。 MySQL浏览器显示列,但没有主键。

解决方案

当您说我无法控制我访问的视图Django的。 MySQL浏览器显示列,但没有主键。



我假设你的意思是这是一个遗留表,你不能添加或更改列?



如果是这样,真的不是一个主键(即使是一个字符串或非int列*),那么表格还没有设置得很好,性能可能会很糟糕。



对你来说没关系。所有你需要的是一列,保证每一行都是唯一的。将其设置为您的模型中的primary_key = True,并且Django将会很高兴。




  • 还有一个其他的可能性将是难以置信的。如果没有列保证是唯一的,那么表可能使用复合主键。也就是说,它指定两个列组合在一起将提供唯一的主键。这是完全有效的关系建模,但不幸的是Django不支持。在这种情况下,除了可以添加另外一个列之外,除了原始SQL之外你不能做很多事情。


class dbview(models.Model):
    # field definitions omitted for brevity
    class Meta:
        db_table = 'read_only_view'

def main(request):
    result = dbview.objects.all()

Caught an exception while rendering: (1054, "Unknown column 'read_only_view.id' in 'field list'")

There is no primary key I can see in the view. Is there a workaround?

Comment:
I have no control over the view I am accessing with Django. MySQL browser shows columns there but no primary key.

解决方案

When you say 'I have no control over the view I am accessing with Django. MySQL browser shows columns there but no primary key.'

I assume you mean that this is a legacy table and you are not allowed to add or change columns?

If so and there really isn't a primary key (even a string or non-int column*) then the table hasn't been set up very well and performance might well stink.

It doesn't matter to you though. All you need is a column that is guaranteed to be unique for every row. Set that to be 'primary_key = True in your model and Django will be happy.

  • There is one other possibility that would be problemmatic. If there is no column that is guaranteed to be unique then the table might be using composite primary keys. That is - it is specifying that two columns taken together will provide a unique primary key. This is perfectly valid relational modelling but unfortunatly unsupported by Django. In that case you can't do much besides raw SQL unless you can get another column added.

这篇关于Django:查询不带主键的只读视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆