Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ForeignKey value for specific field in Django view

Tags:

python

django

I have two models defined in my models.py:

class model1(models.Model):
    name = models.CharField(max_length=100, unique=True)
    desc = models.CharField(max_length=1000, blank=True, null=True)

    def __unicode__(self):
        return u'ID: %s, name - %s, description - %s' % (str(self.pk), self.name, self.desc)

class model2(models.Model):
    description = models.CharField(max_length=500, blank=True, null=True)
    repo_id = models.ForeignKey(model1, to_field='id', db_column="repo_id", null=False)
    content = models.TextField(blank=True)

    def __unicode__(self):
        return u'ID: %s, rpt_repo_id - %s, created_date - %s' % (str(self.pk), str(self.repo_id.pk), self.created_date)

I want to query from model2 to fetch name from model1 where id(pk) of model1 is value from rpt_repo_id of model2. Below query doesn't work here:

saved_reports = models.model2.objects.all()

Although {{ repo_id.name }} works fine in html.

like image 980
Ayush Avatar asked Nov 18 '14 03:11

Ayush


People also ask

What is the difference between ForeignKey and OneToOneField?

A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True , but the "reverse" side of the relation will directly return a single object. In contrast to the OneToOneField "reverse" relation, a ForeignKey "reverse" relation returns a QuerySet .

What is ForeignKey relationship in Django?

Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.

How do I create a one to many relationship in Django?

To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).


1 Answers

You use the same technique in your view, as you did in your template:

saved_reports = model2.objects.all()
for report in saved_reports:
    print('ID: {} Name: {}'.format(report.repo_id.pk, report.repo_id.name))

If you know the id of the model1 object, and want to use that to fetch the model2 object:

model2.objects.filter(repo_id__pk=1)

Django automatically creates reverse relationships for foreign keys. This means that if you have a model1 object, you can get its related model2 object, even if you only defined the foreign key in the model2 object:

model1.objects.get(pk=1).model2_set.all()  # Fetch me all model2 for this model1
like image 65
Burhan Khalid Avatar answered Oct 21 '22 22:10

Burhan Khalid