I have a model called vehicle.
class Vehicle(models.Model):
name = models.CharField(max_length=200)
price = models.models.DecimalField(max_digits=19, decimal_places=2)
the following is sample data stored.
id name price
1 cycle 100
2 bus 10000
3 car 1000
Now i want make invoice based on the order. Someone orders for 2-cycles, 1 bus and 3 cars.
I want to have a model named Invoice which will have 2-cycles, 1 bus and 3 cars. in it.
and at the end create the invoice in the browser like below:
id vehicles no_of_ordered unit_price total_price
1 cycles 2 100 200
2 bus 1 1000 1000
3 car 3 10000 30000
How to create the model:
class Invoice(models.Model):
vehicles = models.ManyToManyField(Vehicle, null=True, blank=True)
After that how to create that list of invoice using the above model
I suggest you create two models representing your invoice and invoice positions. The Invoice model would hold general information (for example a date or the corresponding user) and the InvoicePosition model would hold the instance of Vehicle and the ordered quantity. You could also add the unit price so your previous invoices won't be incorrect after you changed a vehicle's price.
Here's my suggestion in code:
class Invoice(models.Model):
pass
class InvoicePosition(models.Model):
invoice = models.ForeignKey(Invoice, related_name='invoice_positions', on_delete=models.CASCADE)
vehicle = models.ForeignKey(Vehicle, related_name='vehicle_positions', on_delete=models.CASCADE)
quantity = models.PositiveSmallIntegerField()
# You could use the price field to cache the price when the invoice was issued.
price = models.models.DecimalField(max_digits=19, decimal_places=2)
Here's a complete example creating vehicles and an invoice like in your example:
cycle = Vehicle.objects.create(name='cycle', price=100)
bus = Vehicle.objects.create(name='bus', price=10000)
car = Vehicle.objects.create(name='car', price=1000)
invoice = Invoice.objects.create()
invoice.invoice_positions.create(vehicle=cycle, quantity=2, price=cycle.price)
invoice.invoice_positions.create(vehicle=bus, quantity=1, price=bus.price)
invoice.invoice_positions.create(vehicle=car, quantity=3, price=car.price)