如何在Django models.py中更新外键字段?

时间:2017-09-20 05:54:36

标签: python django sqlite

以下是来源: https://docs.djangoproject.com/en/1.8/topics/db/queries/

首先,让我们看一下models.py字段:

from django.db import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()

    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __str__(self):              # __unicode__ on Python 2
        return self.headline

这是如何创建Blog类型的行或对象:

>>> from blog.models import Blog
>>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.')
>>> b.save()

我的问题是如何使用我在Blog类中创建的条目更新Entry对象(存储与Blog相关的外键)的博客列/属性?

2 个答案:

答案 0 :(得分:3)

首先获取Blog对象,然后将其传递给Entry

b=Blog.objects.get(name='Beatles Blog', tagline='All the latest Beatles news.')

e=Entry(blog=b,headline='some headline',body_text='text here',....)
e.save()

答案 1 :(得分:1)

您可以使用documentation中的解决方案。或简答:

b = Blog.objects.get(pk=1)
Entry.objects.filter(pk=17).update(blog=b)
  1. 需要选择要更新的行/行
  2. 使用函数update