更新通过 ForeignKeyField backref 获取的记录是否有效?
Is it a valid use-case to update a record fetched via a ForeignKeyField backref?
我正在使用 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 没有涵盖它?
本例不插入新记录。我认为您的示例要么缺少一些重要信息,要么缺少其他内容。
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
我正在使用 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 没有涵盖它?
本例不插入新记录。我认为您的示例要么缺少一些重要信息,要么缺少其他内容。
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