I use Django 1.9.1, Python 3.5. models.py
:
class Item(models.Model):
name = models.CharField(max_length=200)
price = models.FloatField()
def __str__(self): # __unicode__ on Python 2
return self.name
class Lot(models.Model):
item = models.ForeignKey(Item)
count = models.IntegerField(default = 1)
price = models.FloatField(default = 1) #Price on the moment of buying
def __str__(self): # __unicode__ on Python 2
return self.item.name
def cost(self):
return self.price * self.count
I want to create Lot object wiht default price = item.price
. Ie price on the moment of buying. So I can't obtain price
value from Lot.item.price because it may be different. When code of models.py
is like that:
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 cost(self):
return self.price * self.count
I get following error:
AttributeError: 'ForeignKey' object has no attribute 'price'
How should I correct this code?
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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.