我正在使用Django rest Framework来使api被Android应用程序使用。我有一个活动模型和地点:
class Event(models.Model):
user=models.ForeignKey(User,related_name="%(class)s")
title=models.CharField(max_length=256)
venue=models.ForeignKey(Venue,related_name="%(class)s_venue")
description=models.CharField(max_length=256)
time=models.DateTimeField(max_length=256)
event_pic=models.ImageField(upload_to="photos/event_pic/%Y/%m/%d",null=True,blank=True)
album=models.ForeignKey(Album,null=True,blank=True,related_name="%(class)s_album")
photo=models.ForeignKey(Photo,null=True,blank=True,related_name="%(class)s_photo")
likes=GenericRelation(Like,null=True,blank=True)
comments=GenericRelation(Comments,null=True,blank=True)
这是我的场地模型。
class Venue(models.Model):
name=models.CharField(max_length=256)
longitude=models.FloatField(null=True,blank=True)
latitude=models.FloatField(null=True,blank=True)
def __unicode__(self):
return self.name
我想使用request.user和使用name的场地字段发布到用户字段。是否可以执行此操作,如果是,我该怎么做。 以下是序列化程序和视图。
class WeddingList(generics.ListCreateAPIView):
queryset=Wedding.objects.all()
serializer_class=WeddingSerializer
class WeddingDetail(generics.RetrieveUpdateDestroyAPIView):
queryset=Wedding.objects.all()
serializer_class=WeddingSerializer
class VenueList(generics.ListCreateAPIView):
queryset=Venue.objects.all()
serializer_class=VenueSerializer
class VenueDetail(generics.RetrieveUpdateDestroyAPIView):
queryset=Venue.objects.all()
serializer_class=VenueSerializer
class VenueSerializer(serializers.ModelSerializer):
class Meta:
model=Venue
fields=('name')
class WeddingSerializer(serializers.ModelSerializer):
class Meta:
model = Wedding
excludes=('id',)
答案 0 :(得分:5)
自Django REST Framework 3以来,pre_save
挂钩不再可用。相反,覆盖perform_create
:
def perform_create(self, serializer):
serializer.save(user=self.request.user, ...)
答案 1 :(得分:1)
在您的视图中添加此代码:
def pre_save(self, obj):
# Set here all fields that you need and that aren't already set
obj.user = self.request.user
obj.name = ...
并根据您的需要进行修改:)