Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - use of related_name '+'?

Tags:

python

django

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?

like image 316
zhan Avatar asked Oct 24 '13 02:10

zhan


People also ask

What is related name used for?

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.

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

What is Django ForeignKey model?

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.

What is Db_column?

db_column. The name of the database column to use for this field.


2 Answers

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.

like image 61
Marc Avatar answered Sep 27 '22 17:09

Marc


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.

like image 23
Daniel Quinn Avatar answered Sep 27 '22 17:09

Daniel Quinn