Display all objects, fields of which there is an external link?

For example, it will be easier
class Question(models.Model):
 question_text = models.CharField(max_length=200)
 pub_date = models.DateTimeField('date published')

 def __str__(self):
 return self.question_text

class Choice(models.Model):
 question = models.ForeignKey(Question, on_delete=models.CASCADE)
 choice_text = models.CharField(max_length=200)
 votes = models.IntegerField(default=0)

 def __str__(self):
 return self.choice_text


All you need to withdraw Question, which each have at least one Choice
June 10th 19 at 14:32
2 answers
June 10th 19 at 14:34
Solution
In one request
from django.db.models import Count

Question.objects.annotate(choices_count=Count('choice')).filter(choices_count__gt=0)
Does not work, and complicated. Not SQL easier to write?
Yet ORM to me looks like what a monster compared to normal SQL - Eric.Gulgowski commented on June 10th 19 at 14:37
, then it is better not to use Django, as it is all built around the ORM. - samir39 commented on June 10th 19 at 14:40
on pure SQL will look something like this:
SELECT
q.question_text,
q.pub_date
 COUNT(c.id) AS choices_count
FROM polls_question AS q
LEFT OUTER JOIN polls_choice AS c
 ON (q.id = c.question_id)
GROUP BY q.id
HAVING choices_count > 0;

Still think it's easier? - samir39 commented on June 10th 19 at 14:43
anyway to me it is more clear
But experience does not tell me when and where to use SQL, does it make sense to write logic on the database side or is it all lazitsa on the client?
Do you use PL/pgSQL? - Eric.Gulgowski commented on June 10th 19 at 14:46
I really can't correlate a request ORM with SQL, whether to represent SQL when doing a query on ORM or still thinking on the side of the model objects in python - Eric.Gulgowski commented on June 10th 19 at 14:49
did not understand your question. SQL is used in relational databases. Meaning to write side logic of the database sometimes is, and sometimes not, from the specific logic depends. The main disadvantage of this - "spreading" of logic, which complicates the system maintenance. Plus the fact that sometimes it allows to achieve significant performance gains. PL/pgSQL is used when the logic moves to DB, and DB is PostgreSQL. - samir39 commented on June 10th 19 at 14:52
for the ORM to know SQL and does not necessarily correlate to a chain of operations ORM with a SQL query also in most cases not necessary. But knowledge of SQL allows you to better understand the work of the ORM and is very useful in optimization. - samir39 commented on June 10th 19 at 14:55
June 10th 19 at 14:36
Solution
Question.objects.filter(
pk__in=Choice.objects.values('question__pk').distinct()
)

Find more questions by tags DjangoPython