CodeTalk
CodeTalk

Reputation: 3657

Join records between two tables with Django ORM

I'm slightly unfamiliar with django's ability to join record(s) between (2) tables or more.

For example, I have two tables: img

In plain old SQL, I would do a inner-join on the id field

I have this relationship setup in django's model.py:

class Tld(models.Model):
    domainNm = models.CharField(verbose_name="",max_length=40,unique=True,validators=[RegexValidator('^[a-zA-Z0-9]+\.[a-zA-Z]{1,4}$','format: domain.com only','Invalid Entry')])
    FKtoClient = models.ForeignKey(User) 

the User table is the default django table (created upon initially running python manage.py syncdb)

How do I join these two tables on field DomainNm in django 1.5 ?

Sorry for the newbieness here.

Thank you.

Upvotes: 2

Views: 1023

Answers (1)

Shane
Shane

Reputation: 536

As we discussed in the comments, what you're really wanting is a QuerySet of all Tld objects associated with the currently logged-in User. Luckily, Django makes this fairly trivial since it populates the request.user object with the current User object for you and creates a RelatedManager between the Tld and User models (as shown here by user.tld_set.all()).

views.py:

from django.shortcuts import render

def index(request):
    if request.user.is_anonymous():
        tld_set = []
    else:
        tld_set = request.user.tld_set.all()
    context = {'tld_set': tld_set}
    return render(request, 'index.html', context)

index.html:

<ul>
  {% for tld in tld_set %}
    <li>{{ tld }}</li>
  {% endfor %}
</ul>

The SQL generated from this doesn't contain any JOINs at all since Django already grabbed the User object (and it's associated id) for populating request.user before your view is ever called:

SELECT "rcr_tld"."id", "rcr_tld"."FktoClient_id", "rcr_tld"."domainNm"
FROM "rcr_tld"
WHERE "rcr_tld"."FktoClient_id" = 1  --Django already knows the User's id from request.user.id

Upvotes: 3

Related Questions