Home > Software design >  Access to ForeingKey's model data in Django
Access to ForeingKey's model data in Django

Time:11-28

I need to access to a ForeignKey's model data, but I don't know how. I wrote this as a simple example of what I want to do:

class Model1(models.Model):
name = models.CharField(max_length=100)
phone_number = models.BigIntegerField()

class Model2(models.Model):
model1 = models.ForeignKey(Model1, on_delete=models.CASCADE)
name = model1.name
phone_number = model1.phone_number

It gives me the following error message:

AttributeError: 'ForeignKey' object has no attribute 'name'

CodePudding user response:

If you write model1.name it aims to obtain the attribute of a ForeignKey object, not the object that is referenced by the ForeignKey of a model object.

You can define two properties to obtain the .name and the .phone_number of the related Model1 object:

class Model2(models.Model):
    model1 = models.ForeignKey(Model1, on_delete=models.CASCADE)
    
    @property
    def name(self):
        return self.model1.name
    
    @property
    def phone_number(self):
        return self.model1.phone_number
  • Related