0

I am a beginner in Django and this might be a silly question. I want to access the product table's selling_price & other's data through the order table.

views.py

def createOrder(request):
    form = OrderForm()
    if request.method == 'POST':
        # print('Printing POST:',request.POST)
        form = OrderForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('order')

    context={'form':form}
    return render(request,'accounts/order_form.html',context)  

models.py

class Order(models.Model):
STATUS=(
    ('paid','paid'),
    ('due','due'),
    ('cancel','cancel')
    )
customer=models.ForeignKey(Customer,null=True,on_delete=models.SET_NULL)
product=models.ManyToManyField(Product)
discount=models.FloatField(max_length=200,null=True)
total=models.FloatField(max_length=200,null=True)
paid=models.FloatField(max_length=200,null=True)
due=models.FloatField(max_length=200,null=True)
status=models.CharField(max_length=200,choices=STATUS)
create_date=models.DateTimeField(auto_now_add=True,null=True)


def __str__(self):
    return self.product.name

Here you can see in the model I have a many to many relationship with the product. Can I get the product table's other's details on the template through this relationship?

<div class="form-group col-md-4">
    <label for="name">Product</label>
        <!-- {{form.product|add_class:"form-control select2bs4"}} -->
        {% render_field form.product|add_class:"form-control select2bs4" id='productdropdown' %}
</div>

For say I want to get the selling_price, purchase price of product table instead of a name in the dropdown. How can I do that?

Muhammmed Nihad
  • 161
  • 1
  • 1
  • 12
Fahim Ahmed
  • 111
  • 7

2 Answers2

1

You can access the ManyToMany field details by iterate with the .all attribute https://docs.djangoproject.com/en/3.1/topics/db/models/#extra-fields-on-many-to-many-relationships

For example:

{% for product in order.product.all %}
     {{ product.selling_price }} - {{ product.other_fields_name }}<br/>
{% endfor %}
Linh Nguyen
  • 3,452
  • 4
  • 23
  • 67
1

in your Product class define __str__(self): method like this:

def __str__(self):
    return "%s, %s, %s" % (self.name, str(self.selling_price), str(self.purchase_price))
OlegТ
  • 173
  • 9