0

我有这堂课:

class Contract(db.Model):
    book_number = db.IntegerProperty(required = True)
    initial_page = db.IntegerProperty(required = True)
    final_page = db.IntegerProperty(required = True)
    contract_type = db.StringProperty(required = True)
    parties = db.ListProperty(int)
    date = db.DateTimeProperty (required = True, auto_now = True, auto_now_add = True)

class ContractingParty(db.Model):
    person = db.ReferenceProperty(Person, required=True, collection_name="party_to_contracts")
    contract = db.ReferenceProperty(Contract, required=True)
    condition = db.StringProperty()

我使用此代码创建一个名为Contractwhichparties属性为空列表的实体:

    parties = []
    contract_record = Contract(book_number = int(numBook),
                               initial_page = int(numInitialPage),
                               final_page = int(numFinalPage),
                               contract_type = choosed_contract_type,
                               parties = parties)
    contract_record.put()

但是我必须parties使用 ContractingPerson 实体的 ID 填充该属性。所以,在代码的其他部分,我更新parties了实体的属性Contract,这样:

contracting_party_record = ContractingParty(person = person_key,
                                                      contract = contract_key,
                                                      condition = get_condition)
contracting_party_record.put()
contracting_party_id = contracting_party_record.key().id()
contract = Contract.get_by_id(contract_id)
contract.parties.append(contracting_party_id)
#contract.parties.extend(contracting_party_id)
contract.put()

但是当我查询数据存储时,这样:

parties = db.GqlQuery("SELECT * FROM ContractingParty WHERE contract =:c_key", c_key = contract_key).fetch(20)

我只得到了我创建的最后一个 ContractingParty 实体。似乎contract.parties.append(contracting_party_id)正在用新列表替换旧列表。然后,我尝试使用contract.parties.extend(contracting_party_id). 但是,现在,我得到了这个错误:

File "C:\Users\Py\Desktop\contract\main.py", line 363, in post
    contract.parties.extend(contracting_party_id)
TypeError: 'long' object is not iterable

如何解决?

4

1 回答 1

2

在像 contract.partys.append(contracting_party_id) 这样的列表上附加项目不会取代以前的列表,它也不应该在你的情况下这样做。

你想要做的是使用append而不是extend.

虽然extend期望像另一个列表一样可迭代,但append将一个项目添加到列表中。

>>> l = [1,2,3]
>>> l.append(4)
>>> l
[1, 2, 3, 4] 

>>> l = [1,2,3]
>>> l.extend([4,5,6])
>>> l
[1, 2, 3, 4, 5, 6]
>>> 

这里的文档:http ://docs.python.org/tutorial/datastructures.html

于 2012-08-09T18:34:24.077 回答