我期待使用django REST框架构建“ REST的母亲” rest api。因此,我希望将所有关系表示为url。使用Spring Boot相当容易,但是对于Django REST而言却并非如此。如果我错了,请纠正我。
我必须建模:
const express = require('express');
const { introspectSchema, makeRemoteExecutableSchema, ApolloServer } = require('apollo-server-express');
const { HttpLink } = require('apollo-link-http');
const fetch = require('node-fetch');
const { setContext } = require('apollo-link-context');
async function runServer() {
const httpLink = new HttpLink({ uri: 'http://remote.graphql.server:5555/graphql', fetch });
const link = setContext((request, prevContext) => {
if (prevContext.graphqlContext && prevContext.graphqlContext.headers) {
return {
headers: {
'Authorization': prevContext.graphqlContext.headers.authorization,
}
}
} else {
return {}
}
}).concat(httpLink);
const schema = await introspectSchema(link);
const executableSchema = makeRemoteExecutableSchema({
schema,
link,
});
const server = new ApolloServer({
schema: executableSchema,
context: ({ req }) => ({
headers: req.headers
}),
});
// middleware
const app = express();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(
' Server ready at localhost:4000',
)
)
}
runServer();
现在,我希望模型关系可以像以下模式一样进行序列化(简而言之,我仅将User模型显示为json):
class User(AbstractBaseUser):
username = models.CharField(max_length=25, unique=True)
email = models.EmailField()
created_at = models.DateTimeField(auto_now_add=True)
class Group(models.Model):
admin = models.ForeignKey(User, related_name='groups', on_delete=models.PROTECT)
shared_user = models.ManyToManyField(User, related_name='shared_groups')
name = models.CharField(max_length=25)
description = models.TextField()
created_at = models.DateField(auto_now=True)
我知道我可以通过将其传递到{
"id":1,
"username":"user_1",
"email":"user_1@test.de",
"created_at":"2019-03-08T08:42:34.766951Z",
"_links":{
"self":"http://127.0.0.1:8000/users/1/",
"groups":"http://127.0.0.1:8000/users/1/groups"
}
}
来获取self
网址,但是我喜欢在fields
部分中获取它。我尝试使用_links
添加其他信息。但是我不知道生成代表对象的URL。
有人可以帮忙吗?
通过串行器:
serializers.SerializerMethodField