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
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.
The save method is an inherited method from models. Model which is executed to save an instance into a particular Model. Whenever one tries to create an instance of a model either from admin interface or django shell, save() function is run.
To save data in Django, you normally use . save() on a model instance. However the ORM also provides a . update() method on queryset objects.
Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With