我正在尝试使用DetailView在渲染到模板之前操纵上下文数据。更改主模型(Collection)上的属性可以正常工作,但更改第二个表(Song)上的属性不会改变任何内容。
Models.py
from django.db import models
class Collection(models.Model):
collection_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=250)
artist_display_name = models.CharField(max_length=250)
songs = models.ManyToManyField('Song', through='CollectionSong')
class CollectionSong(models.Model):
collection = models.ForeignKey('Collection')
song = models.ForeignKey('Song')
track_number = models.IntegerField()
volume_number = models.IntegerField()
class Song(models.Model):
song_id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=250)
artist_display_name = models.CharField(max_length=250)
track_length = models.IntegerField()
Views.py
from django.views.generic import DetailView
from .models import Collection
class AlbumView(DetailView):
model = Collection
template_name = 'album.html'
context_object_name = 'collection'
def get_context_data(self, **kwargs):
context = super(AlbumView, self).get_context_data(**kwargs)
context['collection'].name = "YYY" # This works
for song in context['collection'].songs.all():
song.name = "XXX" # This does not work
return context
答案 0 :(得分:0)
这不起作用,因为每次查询集都会从数据库中返回新数据(它在引擎盖下缓存但我们可以认为是新鲜的)所以在将数据保存到数据库之前它不会返回更改的数据。