django foreign key save

I think that getting the artist from the database just to add it to the Mp3 model its unnecessary, if you already have the artist id you should do something like this:

new_mp3 = Mp3(title='Cool song', artist_id=the_artist_id)
new_mp3.save()

Note that the _id in the artist parameter, Django stores foreign keys id in a field formed by field_name plus _id so you can pass the foreign key id directly to that field without having to go to the database again to get the artist object.

If you don't need the artist object for something else in your code you should use this approach.


artist = Artist.objects.get(id=1)  
newMp3 = Mp3(title="sth", artist=artist)

The answer would be:

newMp3=Mp3(title="sth", artist=the_artist)

where 'the_artist' is an actual instance of an Artist

Tags:

Django

Models