django foreign key save

Viewed 37800

I have models for eg 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 need it for 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 than

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

5 Answers

The answer would be:

artist_id = Artist.objects.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!

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