I have the following code:
class Album(models.Model):
name = models.CharField(max_length=255, unique=True, null=False)
rating = models.ForeignKey("Rating", null=False)
class Rating(models.Model):
value = models.IntegerField(null=False, default=0)
What is the best way (in the django/python philosophy) to create an object (Album) and it’s sub object (Rating) and save it?
I have done this:
a = Album()
a.name = "..."
r = Rating()
r.save()
a.rating = r
a.save()
I don’t like this because the part of creating the sub object empty is totally not useful.
I’d prefer some simple way like this – the sub-object should be created automatically:
a = Album()
a.name = "..."
a.save()
You’ll want to look into
signals.Essentially a signals are sent when an Object is saved.
Using a
pre_savesignal you can then create aRatingand associate it to the newAlbumjsut before it is saved for the first time.I haven’t tested this specific code but it should get you in the right direction