Search code examples
djangoaliasrelationdjango-select-related

Create an alias of relation in select_related in Django


i have the model:

Rubric(models.Model):
    name  = models.CharField(max_length=255)

Rubric has seo parameters

class RubricSeo(models.Model):
    rubric = models.OneToOneField(Rubric)
    title  = models.CharField(max_length=255)

To select the rubric with seo i have to use:

rubric = Rubric.objects.select_related('rubricseo',).get(id=rubric_id)

And then use in template:

{{ rubric.rubricseo.title}}

But i need to create an alias to this relation rubricseo (i mean LEFT JOIN rubricseo as seo...), and then use {{ rubric.seo.title}}. But i cant rename the model to simple Seo.

Is it possible to do? Does select_related allow it?


Solution

  • Declare the relation like that:

    rubric = models.OneToOneField(Rubric, related_name='seo')
    

    Then you can access the related model via:

    {{ rubric.seo.title}}