您好我在将views.py(objects.all)中的数据传递给我的ajax时遇到了问题。我想要做的是查询集中的每个对象,我会将其细节附加到我的html中的div中。我尝试序列化它,但我在如何循环序列化的JSON方面遇到了麻烦。有什么建议?请帮助。
jQuery
function getOffers(key){
dict = {
'key':key// pk value of post sent to retrieve offers to it
};
key = "pk";//I actually dont know what to put here
generateCSRFToken();
$.ajax({
url: "/retrieve_offers/",
method: "POST",
data : JSON.stringify(dict),
success: function(data){
data = JSON.parse(data);
console.log(data);
//HOW TO LOOP THROUGH THE DATA AND GET EACH PK
},
error: function(){
}
})
}
views.py
def retrieve_offers(request):
dict = json.loads(request.body)
post_key = Post.objects.get(pk=dict["key"])
offers = Offer.objects.filter(post_id=post_key)
data = serializers.serialize('json',offers)
return HttpResponse(
json.dumps(data),
content_type="application/json"
)
models.py
class Post(models.Model):
date_submitted = models.DateField()
description = models.CharField(max_length=1024)
author = models.ForeignKey(to=User, on_delete=models.CASCADE)
category = models.ForeignKey(to=Category,on_delete=models.CASCADE)
trade_item = models.FileField(null=True,blank=True)
trade_item_name = models.CharField(null=True,max_length=100)
receive_item = models.FileField(null=True, blank=True)
receive_item_name = models.CharField(null=True,max_length=100)
def __str__(self):
return str(self.pk) + " by " + (self.author.username)
@staticmethod
def create(date_submitted, description, author, category):
post = Post()
post.date_submitted = date_submitted
post.description = description
post.author = author
post.category = category
return post
class Offer(models.Model):
date_submitted = models.DateField()
description = models.CharField(max_length=1024)
author = models.ForeignKey(to=User,on_delete=models.CASCADE)
post_id = models.ForeignKey(to=Post,on_delete=models.CASCADE)
image = models.FileField(null=True, blank=True)
item_name = models.CharField(null=True,max_length=100)
的console.log(数据) here is the console.log result image
序列化JSON的示例结果
'[{"model": "bartr.offer", "pk": 26, "fields": {"date_submitted": "2017-03-30", "description": "asdasd", "author": 38, "post_id": 23, "image": "pexels-photo-167810_7vvcPK4.jpeg", "item_name": "something"}}]'