Django:迭代数据库视图的QuerySet [英] Django: Iterate over QuerySet of a database view
问题描述
class MyModel(models.Model):
othermodel = models.ForeignKey(MyOtherModel,related_name ='cached_points')
num_points = models.IntegerField(default = 0)
class Meta(object):
managed = False
请注意 managed = False 声明,以确保Django不会尝试创建或更改表。
除了使用此模型,所有功能都正常用于迭代。例如:
for MyModel.objects.all()中的项目:
....
我得到以下异常:
django.db.utils.ProgrammingError:列app_mymodel.id不存在
LINE 1:SELECTapp_mymodel。id,app_mymodel ...
我理解错误,因为这个(虚拟)表中确实没有列'id',但是迭代器使用它来迭代结果。 p>
如何在没有主键列的情况下迭代此QuerySet?
谢谢,
Erik
我设法通过创建一个值的字典来迭代结果,而不是访问模型字段,方法是使用
items = Items.values中的项目的
('field1','field2',..) ):
item ['field1'] ...#访问数据
我确定还有其他解决方案,但这对我的用例来说最简单。
感谢您指出正确的方向, @ gbs& @Alasdair。
I have a Postgres database view which combines some data from other tables, and I have a Django model to reflect this view (simplified for this question):
class MyModel(models.Model):
othermodel = models.ForeignKey(MyOtherModel, related_name='cached_points')
num_points = models.IntegerField(default=0)
class Meta(object):
managed = False
Note the managed = False statement to make sure Django doesn't try to create or alter the table.
All works fine with using this model, except for iterating over it. When I do, for example:
for item in MyModel.objects.all():
....
I get the following exception:
django.db.utils.ProgrammingError: column app_mymodel.id does not exist LINE 1: SELECT "app_mymodel"."id", "app_mymodel...
I understand the error, as there is indeed no column 'id' in this (virtual) table, but the iterator uses it to iterate over the results.
How can I iterate over this QuerySet without a primary key column?
Thanks, Erik
I managed to iterate over the results by creating a dictionary of the values instead of accessing model fields, by using:
items = MyModel.objects.all()
for item in items.values('field1', 'field2', ..):
item['field1'] ... # Access the data
I'm sure there are other solutions, but this was the easiest for my use case.
Thanks for pointing me in the right direction, @gbs & @Alasdair.
这篇关于Django:迭代数据库视图的QuerySet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!