Closed kiorq closed 7 years ago
anyone?
Hi @kiodou and @dlonli,
I believe you are correct. It should be artist_id
With your definition of has_many in Artist, I think it should be changed to this:
class Artist(Model):
has_many = (('Song', 'songs', 'id', 'artist_id'), 'Concert')
# Tuple definition: (<related model name>, <related objects accessor field>, <model key>, <related model key>)
Note that you could also leave out the Tuple definition completely and get the exact same behavior, i.e.:
class Artist(Model):
has_many = ('Song', 'Concert')
Both "imply" the following object properties:
Artist object has an id. Artist has a list / set of Song objects called 'songs'. Song object has an id. Song object has an artist_id property (reference to Artist object).
With that said, you could do something like this. NOTE: Not fully tested.:
artist = Artist.create(name="Buddy Guy")
artist['songs'].add(Song(title="Stone Crazy"))
artist.save()
artist_id = artist['id']
# Load the artist you just created from the database with the id provided
load_artist = Artist.get(artist_id)
for song in load_artist['songs'].all():
print(song['title']
Note that you're accessing the set of songs by calling load_artist['songs'].all()
. This is because the object returned from the get function is a RelatedObjectHandler instead of the actual set of related Song objects. This is how Remodel handles lazy loading I believe.
I think a key concept here is the "state" of the object. You can't "add" dependent objects unless the parent has been "saved". Meaning the Artist has to have an id assigned before you can add / access the dependent objects.
For example, these are equivalent:
artist = Artist.create(name="Buddy Guy")
artist['songs'].add(Song(title="Stone Crazy"))
artist = Artist()
artist['name'] = "Buddy Guy"
artist.save()
artist['songs'].add(Song(title="Stone Crazy"))
However, if you try accessing the images property without saving first you'll get an error:
artist = Artist()
artist['songs'].add(...)
ValueError: Cannot access related "Song" set: current instance isn't saved
Hope this helps.
Thanks for the help, this gave and experimenting with the code for the past week help me get a better understanding.
Sorry for getting to this issue this slow, but @cemmurphy did an excellent job with his explanations. I will close this for now, but if you have any other questions, feel free to reopen it or open another issue!
Can i get an example what i can do with this:
Does this mean if i add multiple songs
I can access all the songs by:
a["songs"]
???And also,
if \<related objects accessor field> is 'id' (id of artist?) shouldn't the \<related model key> be something like 'artist_id'?