Django: define a name for reverse ForeignKey

2020-08-13 01:52发布

问题:

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()

?

回答1:

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 = ...