1

Is there a way to get all the values of a field form queryset without looping through and adding to array?

I would do like below as simple example.

I have a Report class with a visit FK field.

results = Report.objects.all() visits = [] for res in results: visits.append(res.visit) 

But is there as a way to do something like:

visits = results.visit (and have the same result i would from query loop above).

Edit:

Classes below.

class Report(models.Model): ... completed_at = models.DateTimeField() due_date = models.DateField() planned_date = models.DateTimeField() visit = models.ForeignKey(ReportVisit) class ReportVisit(models.Model): contact_name = models.CharField() time_in = models.DateTimeField() lat_in = models.CharField() long_in = models.CharField() 
3
  • Please share your Report model and the model of res.visit. Commented Apr 9, 2021 at 17:01
  • I have edited to include. I have cut out the stuff I don't think is needed. Commented Apr 9, 2021 at 17:07
  • did you specify a related_name in your ForeignKey? Commented Apr 9, 2021 at 17:07

2 Answers 2

1

You can filter the Visit model with:

ReportVisit.objects.filter(report__isnull=False).distinct()

the .distinct() method [Django-doc] will prevent retrieving the same Visit as many times as there are related Report objects. You can omit this if you want to retrieve the same ReportVisit once per Report.

Sign up to request clarification or add additional context in comments.

4 Comments

Ok, i have actually used similar before but in different use case. I just need to filter based on known set of reports though which im unsure of. Example: results = Report.objects.filter(filters), and get the visits from there. Sorry, i should have put that in question but i didnt think of this way as a solution.
@Spirconi: you can still do that. You then should simply filter with ReportVisit.objects.filter(report__foo__bar=qux) instead of Visit.objects.filter(foo__bar=qux), so look "through" the report model.
Perfect, in my case it was results = ReportVisit.objects.filter( report__isnull=False, report__in=reports )
@Spirconi: I would really advise not to do that, since that creates subqueries, and some databases handles these inefficiently. By filtering on the related model, the database works with a ` JOIN` and WHERE instead.
1

Try from the other direction:

Visit.objects.filter(report__isnull=False) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.