4

I've been looking for a solution to my problem for several days but I can't seem to find exactly what I want. I'd like to make that shopping-cart-like form to book some products in a list. You would check the products that you need and fill in the amount for each one. A reservation can be edited afterwards.

My problem is that reservations and products are linked through a many-to-many intermediary model to have an extra "quantity" field :

class Reservation(models.Model):
    # some fields...
    products = models.ManyToManyField(Product, through='ProductReservation')

class Product(models.Model):
    # some fields...

class ProductReservation(models.Model):
    quantity = models.IntegerField()
    reservation = models.ForeignKey(Reservation)
    product = models.ForeignKey(Product)

I have seen some posts dealing with a similar issue in the admin but here I need to make it available to the client. I have thought about using an inline formset with a custom queryset, but I couldn't manage to make the link between the different classes. I could always populate my fields directly from the submitted data, but I need to reuse that form in multiple views and anyway that doesn't sound very DRY to me.

Thanks for your help !

granarc
  • 41
  • 3

1 Answers1

1

So first you create a Reservation reservation = Reservation.objects.create(some_field=some_value)

Then you create a Product product = Product.objects.create(some_field=some_value)

Finally you can create the link between the two using ProductReservation ProductReservation.create(quantity=100, reservation=reservation, product=product)

Your form can build upon the ProductReservation model. Here it is mentioned how: Accessing Many to Many "through" relation fields in Formsets If things get more complicated, consider building a custom form without the inline form "shortcut".

Community
  • 1
  • 1
markus-hinsche
  • 1,372
  • 15
  • 26