3

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

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I used a slightly different method but this got me on the right track. Thanks @receiver(post_save, sender=Article) def create_catalog(sender, **kwargs): if kwargs.get('created', False): Catalog.objects.get_or_create(name=kwargs.get('instance'), price='10')
The comment inside the code shouldn't read # create catalog object, and associate?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.