D
D
Dmitry2015-03-13 21:24:13
Django
Dmitry, 2015-03-13 21:24:13

How to make a fetch using django ORM?

There are 2 tables, you need to get the sum of numbers from the second table, by sampling from the first.

class Element(models.Model):
    contest = models.ForeignKey(Contest, blank=True, null=True)
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    weight = models.IntegerField(_('Weight'), blank=True, default=1)

class Data(models.Model):
    useractive = models.ForeignKey(UserActiv)
    element = models.ForeignKey(Element, blank=True, null=True)
    date_review = models.DateTimeField(_("Date Review"), auto_now_add=True)
    url_page = models.CharField(max_length=255)
    showing = models.IntegerField(_('Showing'), blank=True, default=0)

Here is the request I wrote:
Element.objects.filter(
  id__in = Data.objects.filter(
    showing = 2,
    useractive = user.id
  ).values_list('element')
).aggregate(sum_weight = Sum('weight'))

I get:
{'sum_weight': 3}
That is, in fact, we get 2 elements, since id__in turns out that it is included in only 2 elements
[<Element: 2>, <Element: 1>]
:
[<Element: 2>,<Element: 2>, <Element: 1>, <Element: 1>, <Element: 1>, <Element: 1>]

And teach:
{'sum_weight': 8}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oscar Django, 2015-03-14
@trec

Element.objects.filter(data__showing=2, data__useractive=user.id).aggregate(sum_weight=Sum('weight'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question