djangodjango-models

Django - access data in a model from a model with a foreign key


I have reduced code to display two models for simplicity. I am very new to Django and have been following the tutorial for the 2nd time but creating my own models.

class Products(models.Model):
        product_name = models.CharField(max_length=50,unique=True,null=False)

        def __str__(self):
            return self.product_name

class Current_tests(models.Model):
        product = models.ForeignKey(Products, on_delete=models.CASCADE)
        no_samples = models.IntegerField(default=0)
        stagecode=models.CharField(max_length=30,default="UPDATE REQUIRED")

        def __str__(self):
            return self.stagecode

Where I have got a bit stuck is on how I access the data in my Products model using the foreign key in Current tests. For example I might want the product_name associated with a specific Current_test data row id or look product_name based on a stage code value.

Equally, how do I get all stagecode for a given product_name.

On the tutorial its done like this:

q = Question.objects.get(pk=1)

# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
<QuerySet []>    

https://docs.djangoproject.com/en/5.1/intro/tutorial02/

When I swap my classes in I get "AttributeError: 'Current_tests' object has no attribute 'product_name_set'.

I have looked at many questions on here that suggest using "related name", "filter" but I have not been able to access data.

Thanks


Solution

  • using your models and expanding a bit on what django.seolpyo.com has already said:

    x = Current_tests.objects.get(pk = <nn>) #this gets a specific record
    print (x.product.product_name) #this prints the product_name associated with the product record you retrieved above.
    

    note that in the above example, you can only return 1 record. if you try to do a .get() on any other field in the current_tests model, you'll possibly get an error as it will return multiple rows (e.g. no unique rows sans pk in that model)

    If getting multiple current_tests records (you'd use a .filter() vs a .get())

    x = Current_tests.objects.filter(product__product_name = '<some product name from the product model>') #this will get all current_tests which have a product name denoted by <some value>
    for rec in x:
        print(f'prod name: {rec.product.product_name} | stage code: {rec.stagecode}')