Найти - Пользователи
Полная версия: peewee и внешний ключ.
Начало » Базы данных » peewee и внешний ключ.
1
Ryoga
Начал разбираться с peewee, и уткнулся в непонятное.
Просветите, кто в курсе.

# -*- coding: utf-8 -*-
from peewee import *
db = SqliteDatabase('temp\\temp.db')
class Cathegory(Model):
    id = IntegerField(primary_key=True)
    name = CharField(max_length=20)
    class Meta:
        database = db
class Assortiment(Model):
    id = IntegerField(primary_key=True)
    name = CharField(max_length=40)
    cathegory = ForeignKeyField(Cathegory, related_name='goods', null=True)
    class Meta:
        database = db
Cathegory.create_table()
Assortiment.create_table()
cath = Cathegory.create(name=u'Чай')
item = Assortiment.create(name=u'Цейлонский', cathegory=cath)

Т.е. в проекте две таблицы, записи из одной (Assortiment) могут содержать ссылку на вторую (Cathegory).
Пускаем, вроде работает:

>>> print cath.name
Чай
>>> print item.name
Цейлонский
>>> print item.cathegory.name
Чай

Чудесно. Теперь делаем выборку по ассортименту:

>>> items = [x for x in Assortiment.select()]
>>> items
[<__main__.Assortiment object at 0x00E92DB0>]
>>> print items[0].name
Цейлонский
>>> print items[0].cathegory
None
>>> print items[0].cathegory.name
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'name'

Упс. Ссылка на категорию куда-то потерялась (аттрибут у None проверил уже для очистки совести)
Что я делаю не так?
Ryoga
В общем, решение случайно нашлось - заменить
id = IntegerField(primary_key=True)
на
id = PrimaryKeyField(primary_key=True)
хотя почему стандартные примеры не работают - непонятно.
https://github.com/coleifer/peewee/issues/185

This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB