使用命令行工具检查模型

时间:2018-04-22 20:58:55

标签: python-3.x django-models

我制作了一个非常简单的模型,并试图从Django命令行工具中查询它。我的模型如下:

from django.db import models

class Finish(models.Model):
    name = models.CharField(max_length=255, blank=False, unique=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

    def __str__(self):
        return "{}".format(self.name)

class Widget(models.Model):
    name = models.CharField(max_length=255, blank=False, unique=True)
    inventory = models.IntegerField(default=0, null=False, blank=False)
    finish = models.ForeignKey('Finish', on_delete=models.CASCADE)
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)

    def __str__(self):
        return "{}".format(self.name)

这是Finish模型中的一个条目:

{
    "id": 1,
    "name": "chrome",
    "date_created": "2018-04-21T21:26:24.214581Z",
    "date_modified": "2018-04-21T21:26:24.214581Z"
}

这是Widget模型的一个条目:

{
    "id": 1,
    "name": "New Chrome Widget",
    "inventory": 123,
    "date_created": "2018-04-21T21:27:57.774508Z",
    "date_modified": "2018-04-21T22:01:46.177778Z",
    "finish": 1
}

这就是我回来的原因:

Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from api.models import *
>>> f = Finish.objects.all()
>>> w = Widget.objects.all()
>>> f
<QuerySet [<Finish: chrome>, <Finish: matte>, <Finish: translucent>, <Finish: silicone>, <Finish: gold>, <Finish: gold-plated>]>
>>> w
<QuerySet [<Widget: New Chrome Widget>, <Widget: Discontinued Matte Widget>, <Widget: Extreme Edition>]>
>>> f.widget_set.all()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'QuerySet' object has no attribute 'widget_set'

文档说明对于给定的模型实例,子属性名称由小写的模型名称+ _set组成,但这对我来说并不适用。我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

我认为您的问题是fQuerySet而不是对象。

来自Django Docs(没有空白):

>>> a.reporter <Reporter: John Smith>

>>> r = a.reporter

>>> r.article_set.all() <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>

尝试:

f = Finish.objects.get(pk=1)

f.widget_set.all()

你应该得到你想要的结果。