[Answer]-Django query select_related span relation

1👍

models.py

class User:
    name = CharField()

    def logs(self):
        return Logs.objects.filter(user=self)

    def info(self):
        return User_Info.objects.filter(user=self)

views.py

users = User.objects.filter()        

template

{% for user in users %}
    {{ name }}

    {% for log in user.logs %}
        //log fields
    {% endfor %}

    {% for info in user.info %}
        //info fields
    {% endfor %}
{% endfor %}

0👍

First of all, the number of database calls doesn’t necessarily relate to the number of lines of code – many methods in the Queryset API are lazy.

It looks like you actually have a one to one relationship between User and User_Info. In this case, you can use a OneToOneField instead of a ForeignKey. Then you can access your info directly from the User model. See
https://docs.djangoproject.com/en/dev/topics/db/examples/one_to_one/

👤Rob

Leave a comment