How to update a foreign key field in Django models.py?

Viewed 26823

Here is the source: https://docs.djangoproject.com/en/1.8/topics/db/queries/

At the beginning, let's look at the models.py field:

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

This is how, a row or an object is created of Blog type:

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

My question is how to update blog column/attribute of Entry object (which stores Foreign Key in relation to Blog) with the entry I created in Blog class?

2 Answers

First get the Blog object and then pass it to 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()

You can use solution from documentation. Or short answer:

b = Blog.objects.get(pk=1)
Entry.objects.filter(pk=17).update(blog=b)
  1. Need to select row/rows which you wanna update
  2. Use function update
Related