Refer to database fields in views.py

I have two tables in a database. In a function in views.py, I want to refer to both tables. Example: I want to loop through all records in table1. For each record, I want to look in table2, and if a field in the table1 record matches a field in the table2 records, I want to add 10 to a value. Any ideas on how to do this would be appreciated.

It’s no different in principle than accessing one table in a view. So, how would you create a view that refers to one table?

If you’re not familiar with how to write the queries, then you should review the appropriate documentation on Making Queries.

Give it a shot, see what you come up with, and we’ll work it from there.

In my function, I would do:

all_table1 = table1.objects.all

all_table2 = table2.objects.all

so to cycle through all of table1’s records, I would probably use a for loop:

for items in all_table1:

But how would I pull out the data in field1 in table1 (one record at a time) to use it to look for things in table2?

Review the Relationship documentation to see how you join two tables together based upon a key field.

And, if you haven’t already done so, I encourage you to completely work through the standard Django tutorial. There are sections in there that work with table relationships and show you how to use the shell to experiment with those tables.

Awesome. Thanks again for all your help.