python - Tango with Django (v1.9/1.10) - 第 5 章,populate_rango 问题

标签 python linux django database model

我会尽量简洁。这个问题的背景是我熟悉 Python,但是我对 django 是全新的。这本书是我第一次接触它,随着我对这本书的研究越来越多,我发现 django 的在线问答不是很笼统,因此很难“只用谷歌搜索”并找到答案。

    我的环境

资源:Tango with Django(1.9/1.10版本)
发行版:基本操作系统,已修补到最新版本
Python版本:3.5
Django 版本:1.11.x

    我的问题

我的错误是什么:django.core.exceptions.FieldError
详细信息是什么:模型页面的字段名称无效:“类别”。
错误是什么意思?:根据 The Docs , 当模型中的某个字段出现问题时会引发此错误..的 列出的原因以下看起来与我的问题相关:

  • 死循环是由排序引起的。
  • 我已经验证了模型中声明字段的顺序与 add_page 的顺序一致。同样,我调试了我的代码,发现所有字段在通过各种函数时看起来都是正确的。但是我在想也许 [this] 可能是问题所在。我认为作品“类别”以某种方式引用了类别类别?总故障排除猜想。
  • 字段名称无效
  • 它总是很简单,我已经检查过了并且变量的命名和用法在整个代码中是一致的。我还根据本书仔细检查了我的代码。一切似乎都井井有条,只是代码无法正常工作。

    回溯

    Traceback (most recent call last):
      File "/home/dj/opt/pycharm-2017.2.3/helpers/pydev/pydevd.py", line 1599, in <module>
        globals = debugger.run(setup['file'], None, None, is_module)
      File "/home/dj/opt/pycharm-2017.2.3/helpers/pydev/pydevd.py", line 1026, in run
        pydev_imports.execfile(file, globals, locals)  # execute the script
      File "/home/dj/opt/pycharm-2017.2.3/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
        exec(compile(contents+"\n", file, 'exec'), glob, loc)
      File "/home/dj/Code/tango-with-django-book/workspace/tango_with_django_project/populate_rango.py", line 83, in <module>
        populate()
      File "/home/dj/Code/tango-with-django-book/workspace/tango_with_django_project/populate_rango.py", line 59, in populate
        add_page(c, p["title"], p["url"])
      File "/home/dj/Code/tango-with-django-book/workspace/tango_with_django_project/populate_rango.py", line 68, in add_page
        p = Page.objects.get_or_create(category=cat, title=title)[0]
      File "/usr/local/lib/python3.5/dist-packages/django/db/models/manager.py", line 85, in manager_method
        return getattr(self.get_queryset(), name)(*args, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 459, in get_or_create
        lookup, params = self._extract_model_params(defaults, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/django/db/models/query.py", line 534, in _extract_model_params
        "', '".join(sorted(invalid_params)),
    django.core.exceptions.FieldError: Invalid field name(s) for model Page: 'category'.
    

    populate_rango.py

    import os
    
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings')
    
    import django
    django.setup() #imports Django projects settings into the context of this script
    
    from rango.models import Category, Page
    
    def populate():
        # First, we will create lists of dictionaries containing the pages we want to add
        # into each category.
        # Then, we will create a dictionary of dictionaries for our categories. 
        # This might seem a little bit confusing, but it allows us to iterate through each data structure, 
        # and add the data to our models. 
    
    
        # List of Dictionaries of "Python" Category pages... Tile:value, URL:value
        python_pages = [
            {"title": "Official Python Tutorial", "url": "https://docs.python.org/2/tutorial/"},
            {"title": "How to think like a Computer Scientist" ,"url": "http://www.greenteapress.com/thinkpython/"},
            {"title": "Learn python in Ten Minutes" ,"url": "https://www.korokithakis.net/tutorials"}
        ]
    
        # List of Dictionaries of "django" Category pages... Title:value, URL:value
        django_pages = [
            {"title":"Official Django Tutorial" ,"url":"https://docs.djangoprojects.com/en/1.11/intro/tutorial01/"},
            {"title":"Django Rocks" ,"url":"https://www.djangorocks.com"},
            {"title":"How to Tango with Django" ,"url":"https://tangowithdjango.com/"}
        ]
    
        # List of Dictionaries of "Other" Category pages... Title:value, URL:value
        other_pages = [
            {"title":"Bottle" ,"url":"http://bottlepy.org/docs/dev/"},
            {"title":"Flask" ,"url":"http://flask.pocoo.org/"}
    
        ]
    
        # A Dictionary of Categories. Passing the pages defined above to the "pages" attribute (making a page) and then applything the tag to which their definied
        # category. 
        cats = {
            "Python": {"pages": python_pages},
            "Django": {"pages": django_pages},
            "Other Frameworks": {"pages": other_pages}
        }
    
        # If you want to add more categories or pages, add them to the 
        # dictionaies above. 
    
        # The code below goes through the cats directory, then adds each category. 
            # and then adds all the associated pages for that category.
            # if you are using python 2.x then use cat.iteritems() see
            # https://docs.quantifiedcode.com/python-anti-patterns/readability
            # for more information about how to iterate over a dictionary properly
    
        for cat, cat_data in cats.items():
            c = add_cat(cat)
            for p in cat_data["pages"]:
                add_page(c, p["title"], p["url"])
    
        # Print out the categories we have added.    
        for c in Category.objects.all():
            for p in Page.objects.filter(category=c):
                print("- {0} - {1}".format(str(c), str(p)))
    
    
    def add_page(cat, title, url, views=0):
        p = Page.objects.get_or_create(category=cat, title=title)[0]
        p.url = url
        p.views = views
        p.save()
        return p
    
    
    def add_cat(name):
        c = Category.objects.get_or_create(name=name)[0]
        c.save()
        return c
    
    
    if __name__ == '__main__':
        print("Starting Rango Population script...")
        populate()
    

    模型.py

    from django.db import models
    
    
    # Create your models here.
    class Category(models.Model):
        name = models.CharField(max_length=128, unique=True)
    
        class Meta:
            verbose_name_plural = 'Categories'
    
        def __str__(self):
            return self.name
    
    
    class Page(models.Model):
        Category = models.ForeignKey(Category)
        title = models.CharField(max_length=128)
        url = models.URLField()
        views = models.IntegerField(default=0)
    
    
        def __str__(self):
            return self.title
    

    不管怎样,即使我重建数据库,这个问题仍然存在。 (rm app.db, makemigrations, 迁移)

    最佳答案

    class Page(models.Model):
        Category = models.ForeignKey(Category)
    

    变量名称区分大小写 - 这包括字段名称和其他类属性。将 Category = models.ForeignKey(Category) 更改为 category = models.ForeignKey(Category) 以适应 model coding style然后重建您的数据库表,您应该可以执行 Page.objects.get_or_create(category=cat...

    关于python - Tango with Django (v1.9/1.10) - 第 5 章,populate_rango 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46331620/

    相关文章:

    python - zip 与 iter( ) 与变量和列表

    linux - 如何删除 vim 7+ 的所有语法颜色真的很烦我

    python - 如何在 Django ORM 中执行 GROUP BY ... COUNT 或 SUM?

    django - 配置 PyDev/Eclipse 以获得最佳 Django 模板编辑(无 Aptana)的技巧?

    python - 使用 cleaned_data 时为 "TypeError: string indices must be integers"

    python - 以编程方式注释 python 脚本

    python - AWS S3特殊字符编码

    linux - 为什么 GNU sort 会在这个特定文件上挂起 10 个小时以上

    Linux 查找二进制文件

    python - 如何对我的 DataFrame 中的值进行分组和计数?