I am using Django rest Framework to make an api to be consumed by an android app. I have a model for events and Venue:
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)
Here is my Venue model.
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
I would like to post to the user field using request.user and the venue field using name.Is it possible to do this and if so how do I do it. Here are the serializers and views.
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',)
Since Django REST Framework 3, the pre_save
hook is not available anymore. Instead, override perform_create
:
def perform_create(self, serializer):
serializer.save(user=self.request.user, ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With