我的models.py:
class CUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), max_length=254, unique=True)
first_name = models.CharField(_('first name'), max_length=30)
last_updated = models.DateTimeField(_('last updated'), default=timezone.now)
class SL(models.Model):
name = models.CharField(max_length=32)
last_updated = models.DateTimeField(default=timezone.now)
uuid = models.UUIDField(primary_key=True)
class Key(models.Model):
last_updated = models.DateTimeField(default=timezone.now)
name = models.CharField(max_length=32, default = 'Unnamed')
sl_uuid = models.ForeignKey(SL, related_name='ssls')
user = models.ForeignKey(CUser)
urls.py:
urlpatterns = [
url(r'^getstate/$', views.GetStateView.as_view(), name='getstate'),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
serializers.py:
class SLSerializer(serializers.Serializer):
queryset=SL.objects.all()
class Meta:
model = SL
fields = (
'name',
'uuid',
'last_updated',
)
class GetStateSerializer(serializers.ModelSerializer):
sls = SLSerializer(many=True)
class Meta:
model = User
fields = tuple(User.REQUIRED_FIELDS) + (
User.USERNAME_FIELD,
'last_updated',
'sls',
)
read_only_fields = (
User.USERNAME_FIELD,
)
views.py:
class GetStateView(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = serializers.GetStateSerializer
permission_classes = (
permissions.IsAuthenticated,
)
def get_object(self, *args, **kwargs):
return self.request.user
我想让json回复:
{
"email":"abc.com",
"first_name":"abc",
"last_updated":"2016-11-02T02:12:36Z",
"sls": [
{
"name":"123",
"last_updated":"2016-11-02T02:12:36Z",
"uuid":"ac9d496d-62ba-45a1-a1ec-e1eca571b656"
},
{
"name":"23",
"last_updated":"2016-11-02T02:12:36Z",
"uuid":"ac9d496d-62ba-45a1-a1ec-e1eca571b656"
}
]
}
我将SL条目视为空:
{
"first_name": "Monica",
"email": "abc@abc.com",
"last_updated": "2016-11-02T02:12:46Z",
"sls": [
{},
{}
]
}
它使用令牌身份验证,并将使用key
表为请求用户(我使用self.request.user)选择所有SL,并将发送用户详细信息以及SL条目。
但我不知道如何去做,所以非常感谢任何帮助。
答案 0 :(得分:0)
如下更新您的序列化器
class SLSerializer(serializers.ModelSerializer):
class Meta:
model = SL
fields = (
'name',
'uuid',
'last_updated',
)
class GetStateSerializer(serializers.ModelSerializer):
sls = SLSerializer(queryset=SL.objects.all(), many=True)
class Meta:
model = User
fields = tuple(User.REQUIRED_FIELDS) + (
User.USERNAME_FIELD,
'last_updated',
'sls',
)
read_only_fields = (
User.USERNAME_FIELD,
)