[Fixed]-Django: two foreign keys to users in model, get the one that's not the user who loaded the page


You can do this as a template tag. Something like:

from django import template

register = template.Library()

def get_other_user_display_name(user, contract):
        return [obj for obj in [contract.employee, contract.employer] \
                if obj != user][0].display_name

        # if you don't like list comprehensions, you could do:
        # set([contract.employee, contract.employer]) - set([user])
        # but I find this syntax to be less than obvious
    except IndexError:
        return ''

Then in your template loop:

{% for contract in user_profile.get_all_contracts %}
    <h2>The other user is {% get_other_user_display_name request.user contract %}</h2>
{% endfor %}

If you’re 100% confident that the contract.employee and contract.employer relationships won’t be null, you can eliminate that IndexError exception handler.

Alternatively, you could do this as an assignment tag if you need to access other properties of the other_user:

def get_other_user(context, contact):
    # you can get request.user from the context

    user = context['request'].user

    return [obj for obj in [contract.employee, contract.employer] if obj != user][0]

Then in your loop you can access whatever properties you want.

{% for contract in user_profile.get_all_contracts %}
    {% get_other_user contract as other_user %}
    <h2>The other user is {{ other_user.display_name }}</h2>
    <p>Their email is: {{ other_user.email }}</p>
{% endfor %}

Leave a comment