我无法使用django rest框架将发布数据发送到api。我使用邮递员发送数据,只有用户部分正在添加到数据库中,而用户的活动却被拒绝。我无法解决问题,谁能帮助我解决这个问题
将发布数据发送到api
{
"name": "karen",
"username": "karen",
"timezone": "US/Samoa",
"activity_periods": [
{
"log_in": "2020-06-09T21:53:25.120897Z",
"log_out": null
},
{
"log_in": "2020-06-09T22:02:35.289891Z",
"log_out": null
},
{
"log_in": "2020-06-09T22:03:36.425212Z",
"log_out": null
}
]
}
但仅存储用户数据,活动被忽略 像这样
{
"name": "karen",
"username": "karen",
"timezone": "US/Samoa",
"activity_periods": []
}
如何向用户添加活动数据...?
models.py
class User(models.Model):
name = models.CharField(max_length=20)
username = models.CharField(max_length=20)
password = models.CharField(max_length=20)
timezone = models.CharField(max_length=32, choices=TIMEZONES, default='UTC')
def __str__(self):
return self.name
class Activity(models.Model):
user = models.ForeignKey(User, related_name="activity_periods",on_delete=models.CASCADE,null=True, blank=True)
log_in = models.DateTimeField(null=True, blank=True)
log_out = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.user.name
serializers.py
class ActivitySerializer(serializers.ModelSerializer):
class Meta:
model = Activity
fields = ['log_in', 'log_out']
class UserSerializer(serializers.ModelSerializer):
# Passing login Logout to User
activity_periods = ActivitySerializer(many=True, read_only=True)
class Meta:
model = User
fields = ['name', 'username','timezone', 'activity_periods']
views.py
class ActivityListView(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
name = "activity-list"
urls.py
path('rest/',views.ActivityListView.as_view())
如何向用户添加活动数据...?
答案 0 :(得分:1)
在您的UserSerializer
中,您有以下一行:
activity_periods = ActivitySerializer(many=True, read_only=True)
由于read_only
设置为True,因此POST
数据将不会被写入数据库。尝试将其设置为False。