django model.objects.all()do no not()给予所有对象

发布于 2025-02-12 08:43:57 字数 412 浏览 1 评论 0原文

在我的Django型号中,我有2个字段。当我在下面执行代码时,它只会打印分辨率字段。如何将所有字段数据获取在列表中?

x = ResolutionsModel.objects.all()
for i in x:
    print(i)

型号

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

In my Django model I have 2 field. 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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

耀眼的星火 2025-02-19 08:43:57

因此,您的模型说,要将自己作为字符串表示为字符串,则应使用resolution的值。因此,通过打印一个实例,这就是您所获得的 - resolution的值。

如果将QuerySet传递到模板,则可以从所有字段中输出值。

为了在Python中进行测试,您必须具体包含每个字段;

x = ResolutionsModel.objects.all()
for i in x:
    print(i.resolution)
    print(i.act_abbreviation)

如果您实际上想在列表中获取数据,则可能需要阅读有关在QuerySet上使用values_list的信息; https://docs.djangoproject.com/44.0/4.0 /ref/models/querysets/#values-list

为了了解Django,您可以也适应您的str方法;

    def __str__(self):
        return f"{self.resolution}, {self.act_abbreviation}"

So your model says that to represent an instance of itself as a string it should use the value of resolution. So by printing an instance, that's what you're getting - the value of 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;

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; 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;

    def __str__(self):
        return f"{self.resolution}, {self.act_abbreviation}"
甩你一脸翔 2025-02-19 08:43:57

在您的情况下:

x = ResolutionsModel.objects.all()

x此处是一个查询集,它返回数据库中的一堆条目,每个条目都是数据库条目:

for i in x:
    print(i)

i # is a database entry, you can access i.resolution & i.act_abbreviation at each loop.

最后,一切都是对象。

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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文