15

I have an Mp3 models which looks like this.

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

and here is how the Artist models looks like:

class Artist(models.Model):
    name=models.CharField(max_length=100,default="Unknown")

I have created Artist with id 1. How I can create a mp3 that is assigned to this artist? (I want to use it for a query like this. for eg)

mp3=Mp3.objects.get(id=50)
mp3.artist

I have tried sth like this

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

but I got this error message

ValueError: Cannot assign "1": "Mp3.artist" must be a "Artist" instance.

I understand the error but still don't know how to solve this. Thanks for any help Best Regards

Daniel
  • 13
  • 4
John
  • 1,350
  • 5
  • 27
  • 49

5 Answers5

39

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.

Ricardo Murillo
  • 2,775
  • 1
  • 18
  • 12
  • 3
    sometimes it may be necessary to ensure the instance with specified id exists. In such cases, fetching the instance will be desirable. Making sure the instance exists and is valid before assigning as foreign key would be a good practice to protect db from wrong data – Mohammed Shareef C Jun 13 '18 at 05:30
20
artist = Artist.objects.get(id=1)  
newMp3 = Mp3(title="sth", artist=artist)
Seitaridis
  • 4,459
  • 9
  • 53
  • 85
3

The answer would be:

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

where 'the_artist' is an actual instance of an Artist

Steve Jalim
  • 11,989
  • 1
  • 37
  • 54
2

First, create or get an artist object.

artist = Artist.objects.create(name="Artist name")

or

artist = Artist.objects.get(id=artist.id) 

Then

newMp3 = Mp3(title="sth", artist=artist)
TheSohan
  • 442
  • 3
  • 18
1

The answer would be:

artist_id = Artist.objects.filter(id=1).first()
new_mp3 = Mp3(title="sth", artist_id=artist_id)
new_mp3.save()

artist_id=artist_id (The left value will get the Artist id from Mp3 fk)

I'm too late... Sorry for that!

LivSith
  • 11
  • 1
  • 4