我有一个存储所有数据的模型。这是我的模型。py:
from django.db import models
class Showing(models.Model):
movie_id = models.CharField(primary_key=True, max_length=11)
movie_title = models.CharField(max_length=100)
image_url = models.TextField(blank=True)
synopsis = models.TextField(blank=True)
rating = models.TextField(default="MTRCB rating not yet available")
cast = models.CharField(max_length=100)
release_date = models.CharField(max_length=50, blank=True)
def __str__(self):
return "{}".format(self.movie_id)
我想检索所有数据并将其传递给上下文,并像这样进行自定义JsonResponse:
"results": [
{
"id": "1eb7758d-b950-4198-91b7-1b0ad0d81054",
"movie": {
"advisory_rating": "PG",
"canonical_title": "ROGUE ONE: A STAR WARS STORY",
"cast": [
"Felicity Jones",
"Donnie Yen",
"Mads Mikkelsen"
],
"poster_portrait": "",
"release_date": "",
"synopsis": "Set shortly before the events of Star Wars (1977), Following the foundation of the
Galactic Empire, the story will center on a wayward band of Rebel fighters which comes together to carry out
a desperate mission: to steal the plans for the Death Star before it can be used to enforce the Emperor's
rule. (Source: Disney Pictures)",
}
},
]
在我的views.py中,我具有此功能来获取所有数据,并尝试仅从模型中检索movie_id。
def show_all_movies(request):
movie = Showing.objects.all()
context = {'result': [{
'id': movie.movie_id,
'movie':}]}
但是我得到了一个错误,“ QuerySet”对象没有属性“ movie_id”。所以我应该如何从数据库中检索数据,以便可以将其解析为json。谢谢。
当我尝试转储时。它返回如下:
"[{\"model\": \"movies.showing\", \"pk\": \"32b05a2f-e52f-55c6-8314-090bdd82e588\", \"fields\": {\"movie_title\": \"0f427f18-23d0-54e3-825e-b56a0f93786f\", \"image_url\": \"http://www.sureseats.com/images/events/movies/thumbnails/geostorm.gif\", \"synopsis\": \"When catastrophic climate change endangers Earth's very survival, world governments unite and create the Dutch Boy Program: a world wide net of satellites, surrounding the planet, that are armed with geoengineering technologies designed to stave off the natural disasters. After successfully protecting the planet for two years, something is starting to go wrong. Two estranged brothers are tasked with solving the program's malfunction before a world wide Geostorm can engulf the planet.(Source: Warner Bros.)\", \"rating\": \"PG\", \"cast\": \"Jeremy Ray Taylor,Gerard Butler,Abbie Cornish\", \"release_date\": \"\"}},
答案 0 :(得分:0)
在您查看的电影对象中是一个查询集。您必须遍历它并处理任何对象。例如这样的
def show_all_movies(request):
movies = Showing.objects.all()
context={'result':[{
'id':movie.movie_id,
'movie': '...'} for movie in movies]}