[Answered ]-Django updating foreignKey field before saving

3πŸ‘

βœ…

You can simply use auto_now in the last_modified field and extend the Page model save method so it calls the Notebook instance save method which will update the last_modified value automatically:

class Notebook(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=200, help_text='Maximum 250 characters')
    slug = models.SlugField(unique=True)
    last_modified = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.title


class Page(models.Model):
    notebook = models.ForeignKey(Notebook)
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique_for_date='pub_date')
    tags = TaggableManager()
    pub_date = models.DateTimeField(default=datetime.datetime.now)

    def __unicode__(self):
        return self.title

    def save(self, *args, **kwargs):
        instance = super(Page, self).save(*args, **kwargs)
        self.notebook.save()
        return instance
πŸ‘€Gonzalo

0πŸ‘

You can do like @Gonzalo answer, just try to replace self.notebook.save() by self.notebook.save(update_fields=['last_modified']) if you are using Django > 1.4

Or you can use the post_save signal

Or you can define last_modified = models.DateTimeField(auto_now=True) in the Page object and get the last modified from NoteBook instance with a simple orm query. (This depends on your requirements)

from django.db.models import Max

class Notebook(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=200, help_text='Maximum 250 characters')
    slug = models.SlugField(unique=True)

    def get_last_modified(self):
        return self.page_set.aggregate(max=Max('last_modified'))['max']

    def __unicode__(self):
        return self.title
πŸ‘€Mounir

-1πŸ‘

The answer above will help but if you would use a form in your template to add page(if you want to users to add pages, probably you will), you will have to do a few more steps.
In adding page part of views.py you should use a code like this:

def tek(request, slug):
    Notebook = get_object_or_404(Notebook, slug=slug)
    form2 = EntryForm(request.POST or None)

    if form2.is_valid():
        page = form2.save(commit=False)
        page.Notebook = Notebook
        Notebook.last_modified = page.pub_date
        Notebook.save()

        return HttpResponseRedirect('/Page/%s'%(page.slug))
    ctx = {}

    return render(request, "app/page.html", ctx)

I don’t know your exact aim on your app so I just wrote a spont code. You should customize it.

πŸ‘€malisit

Leave a comment