Home > Blockchain >  Accessing a query of a Foreign Key
Accessing a query of a Foreign Key

Time:10-10

I have the following model:

class Exercise(models.Model):
    name = models.CharField(max_length = 30, blank=True, null=True)
class Breakdown(models.Model):
    exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='breakdowns',blank=True, null=True)

My question In the views how can I forloop the breakdowns inside exercise.

Here is what I have tried:

class page_details(DetailView):
    model = Workout
    template_name = 'app/page.html'
    context_object_name = 'workout'

    def get_context_data(self, **kwargs):
        exercises = Exercise.objects.filter(workout_id=self.object)
        for e in exercises.Breakdown:
            print(e)

I keep getting AttributeError: 'QuerySet' object has no attribute 'Breakdown'

My question how do I get access to this data.

CodePudding user response:

By using the primary model, you can get the data associated with it from the secondary model. To do this, a special property (object) with the name secondary model_set is created in the primary model by default. In your case, for example: breakdown_set.

primary model.breakdown_set

But since you renamed the property name to: 'breakdowns'. Now to refer to the secondary field it would be:

primary model.breakdowns 

Note that the property is in lower case(the property is created with a small letter).

this code works for me:

ex = Exercise.objects.get(id=1)
for e in ex.breakdowns.all():
   print(e)#prints one object at a time

If you need a request through filter:

test = Exercise.objects.filter(id=1)
for a in test:
   print(a.breakdowns.all())#print QuerySet

if you don't use related_name='breakdowns', then you can use breakdown_set:

exper = Exercise.objects.filter(id=1)
    for a in exper:
        print(a.breakdown_set.all())#print QuerySet
  • Related