【发布时间】:2020-07-06 16:04:37
【问题描述】:
我试图用 drf 在 django 中序列化一个模型,但现在我面临的问题是作为外键的作者被作为整数返回。我使用 Vue.js 作为前端。有人请帮忙
序列化器.py:
from rest_framework import serializers
from .models import Post
class PostSerialiers(serializers.ModelSerializer):
class Meta:
model = Post
fields = "__all__"
Views.py:
from django.shortcuts import render
from .models import Post
from .serializers import PostSerialiers
from rest_framework import viewsets
class PostView(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerialiers
def Home(request):
return render(request, 'Content/Home.html')
models.py:
from django.db import models
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100, blank=True, null=True)
caption = models.CharField(max_length=1200, blank=True, null=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
模板:
<div v-for="post in obj" style="width: 100%;" class="ui card">
<div class="content">
<div class="header">[[post.title]]</div>
<div class="meta">2 days ago</div>
<div class="description">
<p>[[post.caption]]</p>
</div>
</div>
<div class="extra content">
<i class="check icon"></i>
[[post.author]]
</div>
</div>
<script>
function loadDoc() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var app = new Vue({
el: '#root',
delimiters: ['[[', ']]'],
data:{
"obj" : JSON.parse(this.responseText)
}
})
}
}
xhr.open('GET', 'http://localhost:8000/apiposts/', true);
xhr.send()
}
loadDoc()
</script>
请大家帮忙
【问题讨论】:
-
如果您想要该帖子作者的完整详细信息,请在类元中使用 depth=1,然后您可以在 html 中使用 post.author.first_name 或 post.author.last_name, post.author.email
-
@giveJob 不,它不起作用
-
你通过邮递员检查了吗?如果您在字段下方添加 =“all”,depth=1 应该可以工作,还是有任何错误?
-
@giveJob 不,我没有
-
@giveJob 如果可以,请提供帮助。过去 1 个月左右我一直在为此苦苦挣扎
标签: django vue.js django-models django-rest-framework xmlhttprequest