简体   繁体   English

引用外键中指定的模型中的字段

[英]Reference a field from a model specified in Foreign Key

Say I have a car model that looks like this: 假设我有一个看起来像这样的汽车模型:

class Car(models.Model):
     car_model = models.CharField(max_length=100)
     car_number = models.IntegerField()

and I also have a wheel model that now looks like this: 而且我还有一个车轮模型,现在看起来像这样:

class Wheel(models.Model):
    car = models.ForeignKey(Car, on_delete=models.CASCADE)

I want to specify a wheel's model so it has to be the same like its car's model. 我想指定一个车轮的模型,因此它必须与汽车的模型相同。

something like that: 像这样的东西:

class Wheel(models.Model):
    car = models.ForeignKey(Car, on_delete=models.CASCADE)
    wheel_model = car.car_model

How can I achieve this? 我该如何实现? So If my car_model is BMW, I want also to have wheel_model BMW set automatically 因此,如果我的car_model是BMW,我也希望自动设置wheel_model BMW

You can define a property wheel_model on Wheel . 您可以在Wheel上定义属性wheel_model

class Wheel(models.Model):
    car = models.ForeignKey(Car, on_delete=models.CASCADE)

    @property
    def wheel_model(self):
        return self.car.car_model

Now you can access it 现在您可以访问它

wheel_obj.wheel_model

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM