Django,运行makemigrations时出现python语法错误(DecimalField选项)

时间:2016-02-21 08:53:28

标签: python django django-models allegro-pl

在我的应用程序中,我正在调用API以在models.py中为DecimalField创建选项。

# -*- coding: utf-8 -*-
from django.db import models
import re
from suds.client import Client
from datetime import datetime
from django.utils import timezone


class Allegro:
    def __init__(self):
        self.webapi_key = 'hidden key'
        self.country = 1
        self.client = Client('https://webapi.allegro.pl/service.php?wsdl')
        self.client.options.cache.setduration(hours=1)
        self.starting_time = '24h'

    def get_categories(self):
        category_list = self.client.service.doGetCatsData(
            countryId=self.country,
            webapiKey=self.webapi_key
        ).catsList.item

        categories = []
        for item in category_list:
            categories.append({'id': item.catId, 'name': item.catName, 'parent': item.catParent})

        return categories

    # search for free only, with time fixed at 24h. User can set phrase and category only.

    def search(self, category, phrase):
        params = [{
            'item': ({'filterId': 'category', 'filterValueId': {'item': category}},
                     {'filterId': 'startingTime', 'filterValueId': {'item': self.starting_time}},
                     {'filterId': 'search', 'filterValueId': {'item': phrase}})
        }]
        search_raw_result = self.client.service.doGetItemsList(
            countryId=self.country,
            webapiKey=self.webapi_key,
            filterOptions=params,
        ).itemsList.item

        search = []

        for item in search_raw_result:
            search.append({'id': item.itemId, 'name': item.itemTitle,
                           'type': item.priceInfo.item[0].priceType, 'price': item.priceInfo.item[0].priceValue})

        return search


def choices():
    choice_prep = Allegro()
    choice = choice_prep.get_categories()
    choice_list = []
    add = "'"
    for item in choice:
        if item['parent'] == 0:
            item_name = add + item['name'] + add
            choice_list.append([item['id'], item_name])
    return choice_list


class FreeSearch(models.Model):
    a = choices()
    mail = models.CharField(verbose_name='mail', max_length=100)
    phrase = models.CharField(verbose_name='phrase', max_length=150)
    category = models.DecimalField(verbose_name='category', max_digits=6, decimal_places=0, choices=a)
    end_date = models.DateTimeField(verbose_name="Data końcowa", blank=True)
    activation_key = models.CharField(max_length=40, blank=True)
    key_expires = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return '%s, %s, %s' % (self.mail, self.phrase, self.category)

    class Meta:
        verbose_name = "Wyszukanie"
        verbose_name = "Wyszukania"

选择应该是列表,其中只有两个值,id是十进制最多5位数,名称包含Allegro拍卖服务中的类别名称。

在cmd中调用python manage.py makemigrations后发生以下问题:

    C:\Users\Dom\allewatcher>python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python35\lib\site-packages\django\core\management\__init__.py", line
351, in execute_from_command_line
    utility.execute()
  File "C:\Python35\lib\site-packages\django\core\management\__init__.py", line
343, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python35\lib\site-packages\django\core\management\base.py", line 394,
 in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Python35\lib\site-packages\django\core\management\base.py", line 445,
 in execute
    output = self.handle(*args, **options)
  File "C:\Python35\lib\site-packages\django\core\management\commands\makemigrat
ions.py", line 63, in handle
    loader = MigrationLoader(None, ignore_no_migrations=True)
  File "C:\Python35\lib\site-packages\django\db\migrations\loader.py", line 47,
in __init__
    self.build_graph()
  File "C:\Python35\lib\site-packages\django\db\migrations\loader.py", line 176,
 in build_graph
    self.load_disk()
  File "C:\Python35\lib\site-packages\django\db\migrations\loader.py", line 102,
 in load_disk
    migration_module = import_module("%s.%s" % (module_name, migration_name))
  File "C:\Python35\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 658, in exec_module
  File "<frozen importlib._bootstrap_external>", line 764, in get_code
  File "<frozen importlib._bootstrap_external>", line 724, in source_to_code
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "C:\Users\Dom\allewatcher\search\migrations\0001_initial.py", line 20
    ('category', models.DecimalField(decimal_places=0, max_digits=6, verbose_nam
e='category', choices=[[26013, Antyki i Sztuka], [98553, Bilety], [64477, Biuro
i Reklama], [19732, Biżuteria i Zegarki], [73973, Delikatesy], [11763, Dla Dziec
i], [5, Dom i Ogród], [63757, Erotyka], [20585, Filmy], [8845, Fotografia], [9,
Gry], [122640, Instrumenty], [6, Kolekcje], [2, Komputery], [122233, Konsole i a
utomaty], [7, Książki i Komiksy], [3, Motoryzacja], [1, Muzyka], [20782, Nieruch
omości], [1454, Odzież, Obuwie, Dodatki], [16696, Przemysł], [76593, Rękodzieło]
, [10, RTV i AGD], [3919, Sport i Turystyka], [122332, Sprzęt estradowy, studyjn
y i DJ-ski], [4, Telefony i Akcesoria], [1429, Uroda], [55067, Wakacje], [121882
, Zdrowie]])),

                                      ^
SyntaxError: invalid syntax

我也不知道为什么在错误描述中,选择函数中的add变量没有添加引号。

# -*- coding: utf-8 -*-

来自将来导入unicode_literals

来自django.db导入迁移,模型 import django.utils.timezone

类迁移(migrations.Migration):

dependencies = [
]

operations = [
    migrations.CreateModel(
        name='FreeSearch',
        fields=[
            ('id', models.AutoField(auto_created=True, verbose_name='ID', primary_key=True, serialize=False)),
            ('mail', models.CharField(max_length=100, verbose_name='mail')),
            ('phrase', models.CharField(max_length=150, verbose_name='phrase')),
            ('category', models.DecimalField(decimal_places=0, max_digits=6, verbose_name='category', choices=[[26013, Antyki i Sztuka], [98553, Bilety], [64477, Biuro i Reklama], [19732, Biżuteria i Zegarki], [73973, Delikatesy], [11763, Dla Dzieci], [5, Dom i Ogród], [63757, Erotyka], [20585, Filmy], [8845, Fotografia], [9, Gry], [122640, Instrumenty], [6, Kolekcje], [2, Komputery], [122233, Konsole i automaty], [7, Książki i Komiksy], [3, Motoryzacja], [1, Muzyka], [20782, Nieruchomości], [1454, Odzież, Obuwie, Dodatki], [16696, Przemysł], [76593, Rękodzieło], [10, RTV i AGD], [3919, Sport i Turystyka], [122332, Sprzęt estradowy, studyjny i DJ-ski], [4, Telefony i Akcesoria], [1429, Uroda], [55067, Wakacje], [121882, Zdrowie]])),
            ('end_date', models.DateTimeField(blank=True, verbose_name='Data końcowa')),
            ('activation_key', models.CharField(max_length=40, blank=True)),
            ('key_expires', models.DateTimeField(default=django.utils.timezone.now)),
        ],
        options={
            'verbose_name': 'Wyszukania',
        },
    ),
]

2 个答案:

答案 0 :(得分:0)

问题似乎出现在这个项目中:

&#44;

你有一个''符号导致语法错误 - 这个值直接放入python manage.py makemigrations stack 文件中,然后让人觉得列表项有4个项而不是2个。< / p>

要修复它只是从它的值中删除逗号或者以某种方式逃避它(例如使用HTML实体 ('category', models.DecimalField(choices=[[26013, "'Antyki i Sztuka'"], [98553, "'Bilety'"], [64477, "'Biuro i Reklama'"], [19732, "'Bi\u017cuteria i Zegarki'"], [73973, "'Delikatesy'"], [11763, "'Dla Dzieci'"], [5, "'Dom i Ogr\xf3d'"], [63757, "'Erotyka'"], [20585, "'Filmy'"], [8845, "'Fotografia'"], [9, "'Gry'"], [122640, "'Instrumenty'"], [6, "'Kolekcje'"], [2, "'Komputery'"], [122233, "'Konsole i automaty'"], [7, "'Ksi\u0105\u017cki i Komiksy'"], [3, "'Motoryzacja'"], [1, "'Muzyka'"], [20782, "'Nieruchomo\u015bci'"], [1454, "'Odzie\u017c, Obuwie, Dodatki'"], [16696, "'Przemys\u0142'"], [76593, "'R\u0119kodzie\u0142o'"], [10, "'RTV i AGD'"], [3919, "'Sport i Turystyka'"], [122332, "'Sprz\u0119t estradowy, studyjny i DJ-ski'"], [4, "'Telefony i Akcesoria'"], [1429, "'Uroda'"], [55067, "'Wakacje'"], [121882, "'Zdrowie'"]], decimal_places=0, max_digits=6, verbose_name=b'category')), - 但这取决于你如何进一步使用它)

编辑

虽然逗号直接导致问题但似乎问题更深入。迁移的代码的字符串是在没有aphostrophes的情况下生成的,这是导致问题的原因。

我检查了你的代码 - 我创建了应用程序,复制了你的代码并运行了

__init__.py

堆栈是我的应用程序名称BTW

使用aphostrophes生成字符串

makemigrations

如果可能,我建议您删除 your_application / migrations 中的所有文件(避免删除{{1}}!),然后尝试使用标准{{1}}命令重新创建迁移

我一直在1.9.2版本中使用Django,suds 0.4和Python 2.7

答案 1 :(得分:-1)

('category', models.DecimalField(decimal_places=0, max_digits=6, verbose_name='category', choices=[
    [26013, Antyki i Sztuka],
    [98553, Bilety]...

我认为你需要引用这些字符串。

('category', models.DecimalField(decimal_places=0, max_digits=6, verbose_name='category', choices=[
    [26013, "Antyki i Sztuka"],
    [98553, "Bilety"]...