Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: define a name for reverse ForeignKey

I have two models:

class Foo(models.Model):
    foo_field = ...

class Bar(models.Model):
    foo = models.ForeignKey(Foo, on_delete=models.CASCADE)
    bar_field = ...

and I can access all Bar instances related to a Foo with:

Foo.bar_set.all()

Is there a way to change the 'reverse name', like in ManyToManyField, so that I can write:

Foo.bars.all()

?

like image 615
Don Avatar asked Nov 12 '11 10:11

Don


People also ask

What is reverse lookup Django?

Speaking of databases, Django simplifies most of the queries you can make while working with databases. One such query is the reverse look; an example is when we have to get all the objects of a table that are referencing a particular record of either the same table or a different model.

What is the use of related name in Django?

The related_name attribute specifies the name of the reverse relation from the User model back to your model. If you don't specify a related_name, Django automatically creates one using the name of your model with the suffix _set.

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

yes, using related_name

class Foo(models.Model):
    foo_field = ...

class Bar(models.Model):
    foo = models.ForeignKey(Foo, related_name="bars", on_delete=models.CASCADE)
    bar_field = ...
like image 76
second Avatar answered Oct 07 '22 03:10

second