Wednesday, March 2, 2011

Creating one model row from another model save method

Hi community

I have two models in two apps,
first named newsItem

from django.db import models
from datetime import datetime

class newsItem(models.Model):
pubDate = models.DateTimeField('date
published',default=datetime.now())
author = models.CharField(max_length=20, default="author")
title = models.CharField(max_length=200)
text = models.TextField()
snippet = models.TextField(blank=True)
tags = models.ManyToManyField('newsTag', through='TagsToNews')
needsGallery = models.BooleanField()

def __unicode__(self):
return self.title

def save(self, *args, **kwargs):
if len(unicode.strip(self.snippet)) == 0:
self.snippet = ""
super(newsItem, self).save(*args, **kwargs)

and second one in another app called subGallery, which is related to
newsItem via foreign key
from django.db import models
from news.models import newsItem, newsTag

class subGallery(models.Model):
pubDate = models.DateTimeField('date published')
title = models.CharField(max_length=200)
text = models.TextField(blank=True)
tags = models.ManyToManyField(newsTag, through='TagsToGalleries')
newsItem = models.ForeignKey('news.newsItem')

def __unicode__(self):
return self.title

class Meta:
verbose_name_plural = "Galleries"

What I want to do is to create new subGallery whenever newsItem with
"needGallery" field set to true gets created or saved, so I altered
save method of newsItem like this:

def save(self, *args, **kwargs):
if len(unicode.strip(self.snippet)) == 0:
self.snippet = ""
super(newsItem, self).save(*args, **kwargs)

if self.needsGallery:
if not(len(self.subGallery_set.all())):
gallery = subGallery(title = self.title,
pubDate=self.pubDate)
gallery.save()

but when I am creating newsItem through admin page it says: 'newsItem'
object has no attribute 'subGallery_set'
What am I doing wrong?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment