Hi!
First, allow me to describe my models etc:
**models.py**
class Item(models.Model):
name = models.CharField(max_length=50)
...
class Order(models.Model):
table = models.ForeignKey(
"Table", on_delete=models.SET_NULL, null=True, blank=True
)
items = models.ManyToManyField(
Item, through="OrderItem", related_name="orders_items"
...
def get_items(self):
return self.orderitem_set.prefetch_related("item")
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
item = models.ForeignKey(
Item, on_delete=models.SET_NULL, null=True, blank=True
)
quantity = models.PositiveIntegerField(default=1)
date_added = models.DateTimeField(auto_now_add=True)
rating = models.PositiveSmallIntegerField(default=0, null=True, blank=True)
**views.py**
class ReviewOrderView(LoginRequiredMixin, View):
template_name = "menu/submit_review_form.html"
OrderItemFormSet = inlineformset_factory(
Order,
OrderItem,
fields=["rating"],
extra=0,
can_delete=False,
labels="item_names",
)
def get(self, request, *args, **kwargs):
# Please ignore the Table model reference here, it has nothing to do with the problem
order = (
Table.objects.get(id=request.user.table.id).get_order()
)
item_names = order.get_items().values("item__name")
form = self.OrderItemFormSet(
instance=order,
)
return render(request, self.template_name, {"form": form})
def post(request, *args, **kwargs):
pass
As you can see, I have two models in an m2m relationship with a through-model (OrderItem
) that contains additional data, the rating.
I was trying to make a form that will allow users to submit their reviews on items in the order. Since it’s actually a number of small forms with the field rating
that depends on the number of items in the order, I thought the correct way to do so is to implement a formset_factory—or, more specifically, an inlineformset_factory.
I was able to get this:
This correlates with the number of items in order, but I want the actual name of the
Item ("item__name")
instead of the word Rating:
How can I do that?
Will appreciate any help.