1👍
✅
You should override Lot.save
to set the default value for price.
class Lot(models.Model):
item = models.ForeignKey(Item)
price = models.FloatField()
....
def save(self, *args, **kwargs):
if not self.price:
self.price = self.item.price
super(Lot, self).save(*args, **kwargs)
2👍
default
in your model definition is not ‘instance-aware’. I’d suggest overriding the save method of Lot
to pull in price at time of save.
class Lot(models.Model):
item = models.ForeignKey(Item)
count = models.IntegerField(default = 1)
price = models.FloatField(default = item.price) #Price on the moment of buying
def __str__(self): # __unicode__ on Python 2
return self.item.name
def save(self, *args, **kwargs):
if self.item: # verify there's a FK
self.price = self.item.price
super(Lot, self).save(*args,**kwargs) # invoke the inherited save method; price will now be save if item is not null
def cost(self):
return self.price * self.count
- [Django]-Permissions checking in serializer, Django rest framework,
- [Django]-How to change page size in pdf generated by pisa
Source:stackexchange.com