Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access to ForeingKey's model data in Django

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading