Search code examples
pythonpeewee

Is it a valid use-case to update a record fetched via a ForeignKeyField backref?


I'm on peewee 3.14.0 ... is it a valid use case to do something like this? This is ofc a toy example of my actual use-case:

class A(BaseModel):
    id = BigAutoField(primary_key=True)
    a1 = CharField()

class B(BaseModel):
    a = ForeignKeyField(A, backref='bs')
    b1 = CharField()

and then do something like:

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()

to cover this update use-case I need to do the following instead:

a = A.select()...
for b in a.bs:
  q = (B.update({b1: "this however, works"}).where(B.a==a, ..))
  q.execute() 

Is there a way to fix the first approach or is it not covered by peewee?


Solution

  • It does not insert new records in this example. I think your example is either missing some important information or something else is missing.

    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)
    

    This correctly prints:

    t0-x
    t1-x