[英]Django Model.objects.all() doesn't give all the objects
In my Django model I have 2 field.在我的 Django 模型中,我有 2 个字段。 When I execute below code it just prints the resolution field.
当我执行下面的代码时,它只打印分辨率字段。 How can I get the all fields data in a list?
如何获取列表中的所有字段数据?
x = ResolutionsModel.objects.all()
for i in x:
print(i)
models.py模型.py
class ResolutionsModel(models.Model):
resolution = models.TextField(max_length=30,blank=True)
act_abbreviation = models.TextField(max_length=30)
def __str__(self):
return self.resolution
So your model says that to represent an instance of itself as a string it should use the value of resolution
.因此,您的模型说要将自身的实例表示为字符串,它应该使用
resolution
的值。 So by printing an instance, that's what you're getting - the value of resolution
.所以通过打印一个实例,这就是你得到的——
resolution
的值。
If you pass your queryset to a template you could output the values from all the fields.如果将查询集传递给模板,则可以输出所有字段的值。
For the purposes of your test in python you'd have to specifically include each field;为了在 python 中进行测试,您必须专门包含每个字段;
x = ResolutionsModel.objects.all()
for i in x:
print(i.resolution)
print(i.act_abbreviation)
If you actually want to get data in a list, you might want to read about how to use values_list
on a queryset;如果您真的想在列表中获取数据,您可能想了解如何在查询集上使用
values_list
; https://docs.djangoproject.com/en/4.0/ref/models/querysets/#values-list https://docs.djangoproject.com/en/4.0/ref/models/querysets/#values-list
For the purpose of getting to know django you could also adapt your str method;为了了解 django,您还可以调整您的 str 方法;
def __str__(self):
return f"{self.resolution}, {self.act_abbreviation}"
In your case:在你的情况下:
x = ResolutionsModel.objects.all()
The x here is a query set, which returns a bunch of entries from data base, each entry is a database entry:这里的 x 是一个查询集,它从数据库中返回一堆条目,每个条目是一个数据库条目:
for i in x:
print(i)
i # is a database entry, you can access i.resolution & i.act_abbreviation at each loop.
In the end, everything is an object.归根结底,一切都是对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.