Creating multiple objects with one request in Django Rest Framework

3,213 views
Skip to first unread message

Aamu Padi

unread,
Apr 17, 2017, 1:19:23 AM4/17/17
to django...@googlegroups.com

I am using Django as the backend server and Vue.js for the front end Movie app.

I have a Ticket model

class MovieTicket(models.Model):
    show = models.ForeignKey(Show)
    seat = models.ForeignKey(Seat)
    user = models.ForeignKey(User)
    purchased_at = models.DateTimeField(default=timezone.now)
    qrcode = models.ImageField(upload_to='qrcode', blank=True, null=True)
    qrcode_data = models.CharField(max_length=255, unique=True, blank=True)

    class Meta:
        unique_together = ('show', 'seat')

And its related Serializer

class MovieTicketSerializer(serializers.ModelSerializer):
    class Meta:
        model = MovieTicket
        fields = '__all__'

To buy a new Ticket there's a view which is mapped to this url http://dev.site.com/api/movies/buy-ticket/:

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def buy_ticket(request):
    serialized = MovieTicketSerializer(data=request.data)
    if serialized.is_valid():
        serialized.save()
        return Response(serialized.data, status=status.HTTP_201_CREATED)
    return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

Now from the front end (Vue.js) I can create a new movie ticket like this:

const formBody = {
    show: this.$store.state.showSelected.showTime.id,
    user: this.$store.state.user.id,

    // selectedSeats is an array of seats that have been selected by the user. Here I am passing the first seat object.
    seat: this.$store.state.selectedSeats[0].seat.id
};

this.$http.post("http://dev.site.com/api/movies/buy-ticket/", formBody)
    .then(function (response) {
        console.log(response.data);
    })
    .catch(function (response) {
        console.log(response);
    });
return;

If the form was valid, this will create a new MovieTicket Object.

Now, suppose if the user selected multiple seats, I can loop through each selectedSeats array and get the seat ids. But what I am confused is how can I pass multiple seat.id if Django rest framework is only accepting one seat per request?

m712 - Developer

unread,
Apr 17, 2017, 1:25:18 AM4/17/17
to Aamu Padi, django...@googlegroups.com

Hi,
Take a look at https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_many/

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAHSNPWv7yXiCM2VAHU3MBb19nLADU49UH5ZONKW5C7YEUTtfmg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Aamu Padi

unread,
Apr 17, 2017, 11:33:10 AM4/17/17
to django...@googlegroups.com
Hi,

I couldn't find anything useful in that link that can help me solve my problem. What am I missing?

To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

Camilo Torres

unread,
Apr 18, 2017, 6:29:11 AM4/18/17
to Django users
Hi,

May be you can create a new Serializer, including a ListField to get multiple seat IDs:

class ManyMovieTicketsSerializer(serializers.Serializer):
    show = serializers.IntegerField
    user = serializers.IntegerField
    seats = serializers.ListField(child=serializers.IntegerFields)

    def create(self, validated_data):
        iterate over seats and save every instance.

Christian Ledermann

unread,
Apr 18, 2017, 7:16:07 AM4/18/17
to django...@googlegroups.com
maybe
https://github.com/marcgibbons/django-rest-framework-bulk

HTH
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/b8c28522-cf21-4081-9563-97a869f4fa7f%40googlegroups.com.
>
> For more options, visit https://groups.google.com/d/optout.



--
Best Regards,

Christian Ledermann

Newark-on-Trent - UK
Mobile : +44 7474997517

https://uk.linkedin.com/in/christianledermann
https://github.com/cleder/


<*)))>{

If you save the living environment, the biodiversity that we have left,
you will also automatically save the physical environment, too. But If
you only save the physical environment, you will ultimately lose both.

1) Don’t drive species to extinction

2) Don’t destroy a habitat that species rely on.

3) Don’t change the climate in ways that will result in the above.

}<(((*>

Aamu Padi

unread,
Apr 18, 2017, 2:40:38 PM4/18/17
to django...@googlegroups.com
@Camilo Hi, I tried this way

class ManyMovieTicketSerializer(serializers.ModelSerializer):
    seats = serializers.ListField(
        child=serializers.IntegerField(min_value=0, max_value=100)
    )
    class Meta:
        model = MovieTicket
        fields = '__all__'

But I am getting error:

AttributeError at /api/movies/buy-many-tickets/

Got AttributeError when attempting to get a value for field `seats` on serializer `ManyMovieTicketSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `MovieTicket` instance.
Original exception text was: 'MovieTicket' object has no attribute 'seats'.

What am I missing?


> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/b8c28522-cf21-4081-9563-97a869f4fa7f%40googlegroups.com.
>
> For more options, visit https://groups.google.com/d/optout.



--
Best Regards,

Christian Ledermann

Newark-on-Trent - UK
Mobile : +44 7474997517

https://uk.linkedin.com/in/christianledermann
https://github.com/cleder/


<*)))>{

If you save the living environment, the biodiversity that we have left,
you will also automatically save the physical environment, too. But If
you only save the physical environment, you will ultimately lose both.

1) Don’t drive species to extinction

2) Don’t destroy a habitat that species rely on.

3) Don’t change the climate in ways that will result in the above.

}<(((*>
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
Reply all
Reply to author
Forward
0 new messages