In Django1.5 documentation , there is a section about related_name
. the last paragraph is "If you’d prefer Django not to create a backwards relation, set related_name
to '+' or end it with '+'.
For example, this will ensure that the User model won’t have a backwards relation to this model: user = models.ForeignKey(User, related_name='+')
. when should i use the "+" with related_name
?
Using the related_name allows you to specify a simpler or more legible name to get the reverse relation. In this case, if you specify user = models.
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).
ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases. ForeignKey is defined within the django. db. models. related module but is typically referenced from django.
db_column. The name of the database column to use for this field.
From Django docs, a tool to disallow backwards relation, their words:
If you’d prefer Django not to create a backwards relation, set related_name to '+' or end it with '+'.
Above answers are correct, but I wanted to make the answer extra clear for others.
Perhaps when creating a reverse relationship would cause a conflict. Consider the case where you have an abstract model and two sub-classes of said model:
class MyAbstractModel(models.Model):
class Meta(object):
abstract = True
book = models.ForeignKey(Books, related_name="+")
class MyThing(MyAbstractModel):
name = models.CharField(max_length=128)
class MyOtherThing(MyAbstractModel):
number = models.PositiveIntegerField()
Without the use of "+"
, you'd get a naming conflict and Django would refuse to start. Given that you don't actually need it in this case, it makes sense to just skip it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With