【发布时间】:2019-09-10 07:21:51
【问题描述】:
我正在尝试从我的 sqlite 数据库返回项目,以便浏览器中的 url 反映 slug,而不是唯一的帖子 ID。
我之前使用主键进行过这项工作,当单击项目详细信息的超链接时,项目会从数据库中返回 - 但是将所有内容换成 slug 是行不通的。
我有一个 PostListView 在 react 中成功列出了我从数据库中的项目,当我单击其中一个时,浏览器中的 url 字段正确显示了 slug。但是,在基础详细信息视图中不会从数据库返回任何数据。
我正在使用 django 2.2.1,django rest 框架并做出反应。
后端 - django 和 rest 框架模块:
Models.py
class Post(models.Model):
post_id = models.UUIDField(
primary_key=True, default=uuid.uuid4, help_text='Unique ID for this post')
title = models.CharField(max_length=100)
content = models.TextField()
publish_date = models.DateTimeField(auto_now=True)
slug = models.SlugField(default='')
api/views.py
class PostListView(ListAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
class PostDetailView(RetrieveAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer
lookup_field = 'slug'
api/urls.py
urlpatterns = [
path('', PostListView.as_view()),
path('<slug>', PostDetailView.as_view()),
]
api/serializers.py
class PostSerializer(serializers.ModelSerializer):
''' Serialisers will convert our JSON from web into python model '''
class Meta:
model = Post
fields = ('post_id', 'slug', 'title', 'content', 'publish_date' )
lookup_field = 'slug'
前端 - 反应:
PostListView.js
class PostList extends React.Component {
state = {
posts: []
}
componentDidMount() {
// this function gets called everytime the component is mounted(rendered)
axios.get('http://127.0.0.1:8000/api/')
.then(res => {
this.setState({
posts: res.data
});
console.log(res.data);
})
}
render() {
return (
<Post data={this.state.posts} />
)
}
}
Post.js
const Post = (props) => {
const { classes, data } = props;
return (
<List className={classes.root}>
{data.map((item, key) =>
<ListItem alignItems="flex-start" key={item.post_id}>
<ListItemText
primary={<a href={`/${item.slug}`}>{item.title}</a>}
secondary={
<React.Fragment>
<Typography component="span" className={classes.inline} color="textPrimary">
{item.content}
</Typography>
</React.Fragment>
}
/>
</ListItem>
)}
</List>
);
}
PostDetailView.js
class PostDetail extends React.Component {
state = {
post: {}
}
componentDidMount() {
// this function gets called everytime the component is mounted(rendered)
const slug = this.props.match.params.slug;
axios.get(`http://127.0.0.1:8000/api/${slug}`)
.then(res => {
this.setState({
post: res.data
});
})
}
render() {
return (
<Card title={this.state.post.title}>
<p>{this.state.post.content}</p>
</Card>
)
}
}
【问题讨论】:
-
检查浏览器开发工具中的“网络”选项卡 - 它是否发送请求以获取帖子详细信息?如果是 - 服务器响应看起来正确吗?
-
@EugenePrikazchikov GET 请求失败,不确定是我的查找代码还是查找本身失败。