Django在保存之前更新foreignKey字段 [英] django updating foreignKey field before saving

查看:73
本文介绍了Django在保存之前更新foreignKey字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号.py

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

    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__(slef):
        reutrn self.title

很明显,页面属于笔记本,在Notebook模型中我有last_modified字段.

As it is clear, a page belongs to a notebook and I have last_modified field in Notebook model.

当我向数据库中添加新页面时,我希望将last_modified字段更新为插入页面的时间.

When I add a new page to my db, I want last_modified field updated to time of insert of the page.

我知道我必须通过覆盖Page类的save方法来做一些事情.但是不确定如何从不同的类中获取字段.

I know that I have to do some stuff by overrding the save method of Page class. But not sure of how to get fields from different class.

推荐答案

您可以简单地使用

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

这篇关于Django在保存之前更新foreignKey字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆