django foreign key save

后端 未结 5 842
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-18 21:25

I have models for eg like this.

class Mp3(models.Model):
    title=models.CharField(max_length=30)
    artist=models.ForeignKey(\'Artist\')

5条回答
  •  粉色の甜心
    2020-12-18 22:06

    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.

提交回复
热议问题