我在 peewee 3.14.0 上......做这样的事情是一个有效的用例吗?这是我的实际用例的一个玩具示例:
class A(BaseModel):
id = BigAutoField(primary_key=True)
a1 = CharField()
class B(BaseModel):
a = ForeignKeyField(A, backref='bs')
b1 = CharField()
然后执行以下操作:
a = A.select()...
for b in a.bs:
b.b1 = "doesn't work, this will insert a new record rather than update the existing"
b.save()
要涵盖此更新用例,我需要执行以下操作:
a = A.select()...
for b in a.bs:
q = (B.update({b1: "this however, works"}).where(B.a==a, ..))
q.execute()
有没有办法修复第一种方法,或者 peewee 没有涵盖它?
答案 0 :(得分:1)
在这个例子中它不会插入新记录。我认为您的示例要么缺少一些重要信息,要么缺少其他内容。
class User(Base):
username = TextField()
class Tweet(Base):
user = ForeignKeyField(User, backref='tweets')
content = TextField()
db.create_tables([User, Tweet])
u = User.create(username='u1')
for j in range(2):
Tweet.create(user=u, content='t%s' % j)
u = User.get(User.username == 'u1')
for tweet in u.tweets:
tweet.content = tweet.content + '-x'
tweet.save()
for tweet in u.tweets:
print(tweet.content)
这正确打印:
t0-x
t1-x