我有 Farmer 模型,它基本上是 用户 的扩展名 我想使用first_name&来自 Farmer 中用户的last_name,并希望将它们序列化。
我的models.py如下所示:
class Farmer(models.Model):
#Field for refering the default user
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
def __str__(self): # __unicode__ on Python 2
return "%s the farmer" % self.user.username
我的serializers.py如下所示:
class UserSerializer(serializers.ModelSerializer):
first_name = serializers.CharField(required=True)
last_name = serializers.CharField(required=True)
class Meta:
model = User
fields = ('first_name', 'last_name')
class FarmerSerializer(serializers.ModelSerializer):
user = UserSerializer()
...
...
class Meta:
model = Farmer
fields = ('user','birth_date', 'email', 'phone_number')
我按照以下方式获得JSON:
{“user”:{“first_name”:“Jannes”,“last_name”:“Stubbi”}, “birth_date”:“2016-04-13”, “email”:“test@test.com”, “phone_number”:“+ 4912345678” },]
我更愿意将数据作为 :
{“first_name”:“Jannes”,“last_name”:“Stubbi”,“birth_date”:“2016-04-13”,“email”:“test@test.com”,“phone_number”:“+ 4912345678" }
我的views.py
class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
#view to get the details of all the farmers
@api_view(('GET',))
def get_all_farmers_details(request):
#Fetch all the farmers from database
results = Farmer.objects.all()
#Serialize the obtained results
serializer = FarmerSerializer(results, many=True)
return Response(serializer.data)
我怎样才能做到这一点?
答案 0 :(得分:1)
可能你可以尝试这样的事情。
class FarmerSerializer(serializers.ModelSerializer):
first_name = serializers.CharField(source='user.first_name')
last_name = serializers.CharField(source='user.last_name')
..
..
class Meta:
model = Farmer
fields = ('first_name', 'last_name', 'phone_number', 'email')
诀窍是使用'source'属性。
答案 1 :(得分:0)
您可以修改serializer.data
返回的view
:
@api_view(('GET',))
def get_all_farmers_details(request):
#Fetch all the farmers from database
results = Farmer.objects.all()
#Serialize the obtained results
serializer = FarmerSerializer(results, many=True)
userDict = serializer.data.pop("user", None)
if userDict is not None:
serializer.data['first_name'] = userDict['first_name']
serializer.data['last_name'] = userDict['last_name']
return Response(serializer.data)