django updating foreignKey field before saving

南楼画角 提交于 2020-05-16 21:55:26

问题


I have the following models.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

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

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

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.


回答1:


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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/24770424/django-updating-foreignkey-field-before-saving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!