我试图创建一个返回/获取序列化为"http://192.168.11.11:8000/api/address/15"
的函数。
我知道你可以序列化像random
这样的函数,但是我无法弄清楚如何获得我想要的输出。
我想要实现的目标是否明确?我是在正确的轨道上吗?
class Person(models.Model)
name = models.CharField(max_length=40)
desc = models.CharField(max_length=40)
address = models.ForeignKey("Address", null=True, blank=True)
@property
def random(self):
return 'hello there'
@property
def special_address():
# query etc.
if queryset:
return queryset
return False
class PersonSerializer(serializers.ModelSerializer):
special_address = seializer.HyperlinkedSomethingField(possible?)
class Meta:
model = Person
fields = ("name", "desc", "random", "special_address")
期望的输出:
{
"results": [
{
"name": "John Doe",
"desc": "Lorem ...",
"random": "hello there",
"special_address": "http://192.168.11.11:8000/api/address/15"
}
]
}