2015-10-04 32 views
1

我有汽車模型如何在模型定義中訪問ForeignKey的值?

class Automovil(Item_Inventario): 
    brand = models.CharField(max_length=50, default='Acme') 
    model = models.CharField(max_length=50, default='Acme') 

    price = models.FloatField(default=0.0) 

和一個銷售模型

class Sale(models.Model): 
    salesman = models.ForeignKey(settings.AUTH_USER_MODEL) 
    buyer = models.CharField(max_length=50, default='') 
    buyer_id = models.CharField(max_length=50, unique=True, 
           default='00000000') 
    car = models.ForeignKey(settings.MODELO_AUTO) 
    amount = models.FloatField(default=car.price) 
    date = models.DateField(default=timezone.now) 

而且我想與有問題的汽車的價格來計算量,遺憾的是我不能做內部car.price模型定義。那麼我怎麼能做到這一點?

+2

如果您在Automovil類中有價格,爲什麼您在Sale中需要相同的數據? –

+0

由於默認值需要一個實例,因此不可能按照您所做的方式進行設置。在我看來,@ozgur的解決方案就是你要找的東西,然而,我真的不明白爲什麼你需要在db中存儲兩次相同的數據。 – chem1st

回答

3

定義模型時,您可以不涉及這樣的領域。最簡單的方法是重寫Model.save()方法:

class Sale(models.Model): 
    car = models.ForeignKey(settings.MODELO_AUTO) 
    amount = models.FloatField() 
    ... 

    def save(self, *args, **kwargs): 
     self.amount = self.car.price 
     super(Sale, self).save(*args, **kwargs) 
+0

感謝您的解決方案,儘管如此,我不得不使用cleaned_data –

0

我猜你需要計算amount,你可以定義一個signal做到這一點:

#models.py 

from django.db.models.signals import pre_save 

class Automovil()... 

class Sale(models.Model): 
    ... 
    amount = models.FloatField() 
    ... 

def calculate_amount(sender, instance, *args, **kwargs): 

    instance.amount = instance.car.price 

pre_save.connect(calculate_amount, sender=Sale) 
相關問題