首页 > django后台如何更新其他模型字段?

django后台如何更新其他模型字段?

我的django版本是1.8.4,下面是偶博客的两个模型。

class Category(models.Model):
    title = models.CharField('分类标题',max_length=255)
    count = models.CharField('分类文章数',max_length=255)

class Article(models.Model):
    category = models.ForeignKey(Category,verbose_name='分类')
    title = models.CharField('文章标题',max_length=255)
    content = models.TextField('文章内容',max_length=255)

我的问题是,如何在django admin添加文章时,分类的count字段能+1,删除文章时-1,我看到有个save方法,貌似是操作self的,有没有操作其他模型的方法呢?先谢。


视图层是可以读写model的外键的字段值的,官方文档中可看。

# Declare the ForeignKey with related_query_name
class Tag(models.Model):
    article = models.ForeignKey(Article, related_name="tags", related_query_name="tag")
    name = models.CharField(max_length=255)

# That's now the name of the reverse filter
Article.objects.filter(tag__name="important")
【热门文章】
【热门文章】