Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How do i create a foreign key without a related name?

Tags:

django

I run into the problem of clashing automatic related names, and often having a foreign manager installed on the related model is not needed.

For example, it would be great if i could:

class ExtraWidgetThingy(models.Model):
    product = models.ForeignKey("product.Product")
    also_tastes_good_with = models.ForeignKey(
        "product.Product", related_name=None)

instead of related_name='extrawidgetthingys_that_also_tastes_good_with_this'

like image 930
leech Avatar asked Mar 17 '11 21:03

leech


People also ask

What is related name in ForeignKey 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.

Can a model have two foreign keys in Django?

Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example), or you must explicitly specify the foreign keys Django should use for the relationship using ManyToManyField.

Does Django automatically index foreign keys?

Django automatically creates an index for all models. ForeignKey columns. From Django documentation: A database index is automatically created on the ForeignKey .


1 Answers

From the docs:

If you'd prefer Django didn't create a backwards relation, set related_name to '+'.

like image 152
Ignacio Vazquez-Abrams Avatar answered Oct 21 '22 20:10

Ignacio Vazquez-Abrams