I have a Django Model defined as a ServiceEvent, and another defined as Part.
class ServiceEvent(Model):
date = DateTimeField(null=False, blank=False, db_column='date',
default=datetime.now())
vehicle = ForeignKey(Vehicle, on_delete=models.CASCADE)
description = TextField(null=True, blank=False, db_column='description')
# The contents of the notifications to create for this event.
notification_contents = TextField(null=True, blank=False,
db_column='notification_contents')
# The mileage the event should occur.
target_mileage = DecimalField(max_digits=10, decimal_places=2,
null=True, blank=False,
db_column='target_mileage')
# The mileage at the time of the event.
event_mileage = DecimalField(max_digits=10, decimal_places=2,
null=True, blank=False,
db_column='event_mileage')
class Part(Model):
part_number = CharField(max_length=100, null=False, blank=False,
db_column='part_number')
description = CharField(max_length=100, null=False, blank=False,
db_column='description')
price = DecimalField(max_digits=10, decimal_places=2, null=False,
db_column='price')
service_event = ForeignKey(ServiceEvent, on_delete=models.CASCADE)
There can be multiple Parts per ServiceEvent.
What is a way to store a column in the ServiceEvent table that contains the price of all of the parts added up that belong to a given event?
I would like to do this for efficiency.
I want to be able to do something along the lines of:
price = service_event_obj.total_price
I'm using SQLite.
You could do this with a
TRIGGERBUT there is likely no need as thesumof the prices could be generated/calculated/derived from existing data when extracting data.Demonstration
Here's a demonstration based loosely upon the schema according to your code:-
This results in:-
Extra
You could even do something along the lines of the following:-
Which would produce a crude invoices detailing the parts and the total:-