[Django]-Django query Select X from Table where Y = Z

2👍

Another approach is to use Django’s values and values_list methods. You provide the field name you want data for.

values = Table_A.objects.filter(name=B_name).values('code')

This returns a dictionary with only the code values in it. From the django documentation, https://docs.djangoproject.com/en/2.1/ref/models/querysets/#django.db.models.query.QuerySet.values

Or you can use values_list to format the result as a list.

values = Table_A.objects.filter(name=B_name).values_list('code')

This will return a list of tuples, even if you only request one field. The django documentation, https://docs.djangoproject.com/en/2.1/ref/models/querysets/#django.db.models.query.QuerySet.values_list

To try to make this a little more robust, you first get your list of named values from Table_B. Supplying flat=True creates a true list, as values_list will give you a list of tuples. Then use the list to filter on Table_A. You can return just the code or the code and name. As written, it returns a flat list of user codes for every matching name in Table A and Table B.

b_names_list = Table_B.objects.values_list('name', flat=True)
values =Table_A.objects.filter(name__in=b_names_list).values_list('code', flat=True)
👤Rachel

2👍

Suppose name of your tables are A and B respectively then:

try:
    obj = A.objects.get(name='John')
    if B.objects.filter(name='John').exists():
        print obj.code # found a match and now print code.      
except:
    pass 

1👍

Let’s suppose TableA and TableB are django models. Then, your query, may look like this:

a_name = 'John'

it_matches_on_b = ( Table_B
                   .objects
                   .filter(  name = a_name )
                   .exists()
                  )

fist_a = ( Table_A
            .objects
            .filter(  name = a_name )
            .first()
          )

your_code = fist_a.code if it_matches_on_b and fist_a != None else None

I don’t comment code because it is self-explanatory. But write questions on comments if you have.

0👍

B_name = ‘whatever’
Table_A.objects.filter(name = B_name)

The above is the basic query if you want to get the db fields values connected to name value from Table_A, based on the fact that you know the name value of Table_B

To get the value:

obj = Table_A.objects.get(name = B_name)

print(obj.name)
print(obj.code) # if you want the 'code' field value
👤Zollie

Leave a comment