Django - Reference data of another model using a foreign key

advertisements

I'm new to Django so please tell me if I'm not on the right track. I have a Django project that I'm building and just wanted to ask what is the correct Django way to retrieve data from one model and use it in another.

I have a for loop to assign the required fields to variables but I was looking for a cleaner solution and if one exists, one that uses the foreign key.

Here's an example of the code involved:

#MODELS

class Class1(models.Model):
    tag_number = models.CharField(max_length = 300, null = True, blank = True)
    example1 =  models.CharField(max_length = 300, null = True, blank = True)
    example2 =  models.CharField(max_length = 300, null = True, blank = True)

class Class2(models.Model):
    tag = models.ForeignKey(Class1, related_name = 'tag_foreignkey')
    example3 =  models.CharField(max_length = 300, null = True, blank = True)
    example4 =  models.CharField(max_length = 300, null = True, blank = True)

#VIEWS - This view is for Class2 but referencing fields from Class1

tag_number = str(instrumentform.cleaned_data['tag'])
query_results = Class1.objects.filter(tag_number = tag_number)
for query_result in query_results:
        example5 = query_result.example1
        example6 = query_result.example2

The above works but I assume it's not the Django way of doing things and is not taking advantage of the foreign key.

If someone could give me a nudge in the right direction that would be greatly appreciated.


Still, not hundred percent know what you want, since there are some missing info out there. For you Class1, You should do what you have done to Class2, using foreign key to store tag.

For you code at bottom, there is a easy way to do it. (Assume you have used foreign key)

tag_number = int(instrumentform.cleaned_data['tag'])
for query_result in Class1.objects.filter(tag = tag_number).values_list('example1', 'exmaple2'):
    example5, example6 = query_result