我的模型上有两个必填字段,我想在我的ModelViewSet的pre_save方法中填充.尽管在那里设置了它们,但是在提交.create()请求时,我仍然会收到一个错误,即需要这两个字段,因此无法创建我的对象.
我对此做了一些研究,似乎它与调用pre_save之前执行的is_valid()检查有关…我发现的每个堆栈溢出文章的推荐解决方案:
Django REST Framework, pre_save() and serializer.is_valid(), how do they work?
Django REST Framework serializer field required=false
似乎是要覆盖get_validation_exclusions方法.然而,这似乎仍然不适合我…我在想这可能与我的模型继承有关?您可以提供的任何帮助将不胜感激!这就是我正在使用的 –
serializers.py
class DaytimeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Daytime
def get_validation_exclusions(self):
exclusions = super(DaytimeSerializer, self).get_validation_exclusions()
return exclusions + [ 'creation_datetime', 'creator_userprofile' ]
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
phone_number = models.CharField(max_length=12)
friends = models.ManyToManyField('self', related_name = 'friends')
field4 = models.CharField(max_length=300, blank=True)
def __unicode__(self):
return self.user.username + ' UserProfile'
class Activity(models.Model):
field1 = models.CharField(max_length=300)
field2 = models.CharField(max_length=300, blank=True)
creation_datetime = models.DateTimeField()
creator_userprofile = models.ForeignKey(UserProfile)
field3 = models.ManyToManyField('self')
field4 = models.BooleanField()
field5 = models.CharField(max_length=300, blank=True)
def __unicode__(self):
return self.field1 + ' | ' + self.creator_userprofile.user.username
class Meta:
abstract = True
class Daytime(Activity):
field6 = models.ManyToManyField(UserProfile, related_name='abc')
field7 = models.BooleanField()
myviewsfile.py
class DaytimeViewSet(viewsets.ModelViewSet):
queryset = Daytime.objects.all()
serializer_class = DaytimeSerializer
def pre_save(self, obj):
obj.creator_userprofile = UserProfile.objects.get(user__username = self.request.user)
obj.creation_datetime = timezone.now()
最佳答案 所以我从现在做我希望它会做的事情来解决这个问题,但我并不完全确定这是最好的方法.
将这两行添加到DaytimeSerializer是更改:
class DaytimeSerializer(serializers.HyperlinkedModelSerializer):
creator_userprofile = serializers.HyperlinkedRelatedField(source='creator_userprofile',view_name="userprofile-detail")
creation_datetime = serializers.Field(source='creation_datetime')
为什么我需要明确告诉序列化器creation_datetime字段应该来自传入的JSONs creation_datetime?它隐含在所有其他领域……我在这里错过了一些东西吗?
此外,现在我这样做了,我不再需要覆盖get_validation_exclusions方法.我删除了那一点.