【发布时间】:2021-09-05 03:21:51
【问题描述】:
我正在尝试使用 slug 访问我的 django + vue3 项目中的模型的详细信息。
后端
在我的models.py 我有
from django.db import models
from django_extensions.db.fields import AutoSlugField
class Magazine(models.Model):
title = models.CharField(max_length=255, unique=True)
description = models.TextField(blank=True, null=True)
slug = AutoSlugField(populate_from=['title'])
def __str__(self):
return self.title
在我的serialisers.py
from rest_framework import serializers
from .models import Magazine
class MagazineSerializer(serializers.ModelSerializer):
class Meta:
model = Magazine
fields = (
'id',
'title',
'description',
'slug'
)
在我的views.py
from django.shortcuts import render
from rest_framework import viewsets
from .models import Magazine
from .serializers import MagazineSerializer
class MagazineViewSet(viewsets.ModelViewSet):
serializer_class = MagazineSerializer
queryset = Magazine.objects.all()
前端
在我的router/index.js 我有
{
path: '/magazines/:slug',
name: 'Magazine',
component: Magazine,
meta: {
requireLogin: true
}
}
在我的Magazine.vue 页面中,我有
<template>
<div class="bph-content">
<h1>{{ magazine.title }}</h1>
<h1>{{ magazine.slug }}</h1>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'Magazine',
data() {
return {
magazine: {}
}
},
mounted() {
this.getMagazine()
},
methods: {
async getMagazine() {
const magazineSlug = this.$route.params.slug
await axios
.get(`/api/v1/magazines/${magazineSlug}`)
.then(response => {
this.magazine = response.data
})
.catch(error => {
console.log(error)
})
}
}
}
</script>
在 http://localhost:8080/magazines/<slug-magazine> 我收到 404 错误,但在 http://localhost:8080/magazines/<id> 我正确获得了各种期刊的详细信息(即使我使用的是 slug!)
如何通过http://localhost:8080/magazines/<slug-magazine>获取杂志详情?
【问题讨论】:
-
前端无关紧要。在前端调用它是
id还是slug都没有关系。这取决于你的后端。它应该接受 api 请求中的 slug。 -
您的建议足以告诉我正确的方向。我修复了 django 序列化程序并查看并解决了问题。非常感谢!现在不知道怎么处理这个问题:是删除还是自己回答
-
很高兴你解决了它。欢迎在 SO 上进行自我回答。考虑更新问题以使用带有相关标签的后端反映您的情况。