python - 更新通过 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
推荐阅读
- redux - 想要从本地存储中获取项目并显示自定义状态(如果有)
- angular - 有一个json数据以及如何在angular 12 html中使用点路径绑定json字段?
- javascript - 在 ASP.NET MVC 中提交表单后如何弹出对话框?
- svelte - Svelte - 使用绑定在一起的两个输入来控制单个商店项目
- javascript - Java脚本,节点js函数没有返回预期的内容
- java - 从其他类调用方法时出现类循环问题
- r - 从具有多个坐标的数据框创建 sf 对象 | 顺丰
- excel - Excel 连续工作天数至少 60 分钟
- database - 续集,创建新用户并在一个查询中分配已创建的角色?
- python - 将具有“int”“类型”的变量放入方法的参数即“.remove()”时获取“未知变量x”或“ValueError”