Reputation: 5467
I have an Article model which has a OnetoOne relationship with a Catalog Model. Is it possible to create an instance of Catalog from within the save method of the Article. I'd like to attach an Article with a Catalog of the same name, it would be easiest to create these at the same time.
Here is my Catalog class:
class Catalog(models.Model):
name = models.CharField(max_length=100)
price = models.IntegerField
def __unicode__(self):
return self.name
Article Class:
class Article(models.Model):
catalog = models.OneToOneField(Catalog, related_name='article_products', blank=True, null=True)
title = models.CharField(max_length=200)
abstract = models.TextField(max_length=1000, blank=True)
full_text = models.TextField(blank=True)
proquest_link = models.CharField(max_length=200, blank=True, null=True)
ebsco_link = models.CharField(max_length=200, blank=True, null=True)
def __unicode__(self):
return unicode(self.title)
def save(self, *args, **kwargs):
self.full_text = self.title
super(Article, self).save(*args, **kwargs)
I'd like to some logic similar to this within the save method: I'm not sure if it's possible though
cat = Catalog.create(title = self.title)
cat.save()
Upvotes: 3
Views: 4065
Reputation: 99620
You could instead use post_save
signal for creating catalog objects at the time of creation of article objects. This would ensure creation of the catalog objects, without having to include non-relevant code in the article models' save method.
from django.db.models.signals import post_save
# method for updating
def create_catalog(sender, instance, created, **kwargs):
if instance and created:
#create article object, and associate
post_save.connect(create_catalog, sender=Article)
Upvotes: 5