logo
down
shadow

Django: QuerySet with ExpressionWrapper


Django: QuerySet with ExpressionWrapper

Content Index :

Django: QuerySet with ExpressionWrapper
Tag : python , By : druta
Date : January 12 2021, 01:40 AM

I wish did fix the issue. An .annotate(..) means you add an attribute to every Ticket object. What you here want is probably want is .aggregate(..):
max_total_gross = event.tickets.aggregate(
    max_total_gross=Sum(
        F('quantity') * F('price_gross')
    )
)['max_total_gross']
Event.objects.annotate(
    max_total_gross=Sum(
        F('tickets__quantity') * F('tickets__price_gross')
    )
)

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Django Queryset .last() method on processed queryset returning incorrect element


Tag : django , By : Manik
Date : March 29 2020, 07:55 AM
With these it helps If anyone put any thought into this edge-case, the reasons would most likely be a combination of consistency and performance.
First of all, you generally can't evaluate the entire queryset just to get the last element without imposing a huge performance penalty. Person.objects.order_by('order').last() should get one row, not the entire table -- which could contain millions of rows. So in case of an unevaluated queryset, you need to reverse the order in SQL and get the top element. This will always suffer from the problem you describe.
people = Person.objects.order_by('order')
p1 = people.last()
bool(people)
p2 = people.last()

Tag : python , By : Dov
Date : March 29 2020, 07:55 AM
wish helps you Given a URL like this: , Well, here's the answer. Use "Q" objects! :-)
...
foo = self.request.GET.getlist('foo')
if (len(foo) > 0):
  q = Q()
  for _foo in foo:
    q |= Q(foo__iexact=_foo)
  queryset = queryset.filter(q)
...
http://..../fl/users/?foo=&bar=some_bar
<QueryDict: {'foo': [''], 'bar': ['some_bar']}>
...
foo = self.request.GET.getlist('foo')
if (len(foo) > 0):
  q = Q()
  for _foo in foo:
    if (_foo == ''):
      q |= Q(foo=None)
    else:
      q |= Q(foo__iexact=_foo)
  queryset = queryset.filter(q)
...

Django ORM DateTimeField ExpressionWrapper QuerySet annotation


Tag : django , By : Senthil
Date : March 29 2020, 07:55 AM
I hope this helps . I have made it work by changing the query annotation to the following:
    sprints = Sprint.objects.annotate(
        duration=models.Case(
            models.When(
                Q(started__isnull=False) &
                Q(done__isnull=False),
                then=(models.F('done') - models.F('started')),
            ),
            models.When(
                Q(started__isnull=False) &
                Q(done__isnull=True),
                then=(Now() - models.F('started')),
            ),
            output_field=models.DurationField()
        )).values_list('name',
                       'planned',
                       'started',
                       'done',
                       'duration')

how to implement ExpressionWrapper, F and Sum properly in django


Tag : django , By : greggerz
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I have two models Product and Damaged. Product has quantity of an item and Damaged has the number of damaged quantity of that item. In my template list_product I have listed total quantity of each product. When I add number of damaged_quantity into the Damaged model it should be deducted from the number of total quantity in Product. I have implemented the following code. Everything works fine. The only problem I am having is if the total number of quantity in Product is equal to number of damaged_quantity from Damaged it doesn't show 0 in the template of product_list. How to solve it? , You can try like this:
products = Product.objects.annotate(damaged_product_quantity=Sum(
'damagedproducts__damaged_quantity')).annotate(
real_quantity=F('quantity')-F('damaged_product_quantity'))
from django.db.models import Value, When, Case

products = Product.objects.annotate(
    damaged_product_quantity=Sum('damagedproducts__damaged_quantity'))

updated_product = products.annotate(
    real_quantity = When(
        Case(quantity__gt=F('damaged_product_quantity'), then=F('quantity')-F('damaged_product_quantity')),
        Case(quantity__lte=F('damaged_product_quantity'), then=Value(0))
    )
)

How to return multiple queryset object or add queryset result from get_queryset method in Django


Tag : python , By : Cadu
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Django Rest Framework - Testing client.login doesn't login user, ret anonymous user
  • Running dag without dag file in airflow
  • Filling across a specified dimension of a numpy array
  • Python populating dataframe in pandas from text files
  • How to interpolate a single ("non-piecewise") cubic spline from a set of data points?
  • Divide 2 integers (leetcode 29) - recursion issue
  • Can someone explain why do I get this output in Python?
  • How do I scrape pdf and html from search results without obvious url
  • Is there a way to automatically make a "collage" of plots with matplotlib?
  • How to combine multiple rows in pandas with shared column values
  • How do I get LOAD_CLASSDEREF instruction after dis.dis?
  • Django - How to add items to Bootstrap dropdown?
  • Linear Regression - Does the below implementation of ridge regression finding coefficient term using gradient method is
  • How to drop all rows in pandas dataframe with negative values?
  • Most Efficient Way to Find Closest Date Between 2 Dataframes
  • Execution error when Passing arguments to a python script using os.system. The script takes sys.argv arguments
  • Looping through a function
  • Create a plot for each unique ID
  • a thread python with 'while' got another thread never start
  • Solution from SciPy solve_ivp contains oscillations for a system of first-order ODEs
  • trigger python events driven by selenium controlled browser
  • Passing line-edits to a contextmanager to set validators
  • Python: globals().items() iterations try to change a dict
  • Is it possible to specify starting values for each parameter (instead of bounds) for scipy's differential evolution?
  • why datetime.now() and constructed datetime using all fields(like year,month...) of now has big timedelta?
  • MySQL multiple table UPDATE query using sqlalchemy core?
  • find if a semantic version is superset of of another version python
  • Type checking against dynamically created objects
  • Struggling with simple reverse function
  • Is there a function for finding the midpoint of n points on sklearn.neighbors.NearestNeighbors?
  • How to set max number of tweets to fetch
  • PYTHON 3.7.4 NOT USING SQLITE 3.29.0
  • How to replace Nan value with zeros in a numpy array?
  • How to speed up calculating variance among sparse matrix
  • cupy code is not fast enough compared with numpy
  • How to count frequency of select values in Python pandas dataframe
  • Scrape Span Text from Google
  • Python watchdog, watch a directory and rename file on event.modification
  • Filtering rows in DataFrame with dependent conditions
  • How to check if a character is a not a part of number or URL in string?
  • Compare corresponding elements of a list
  • Python misinterprets 3 character string as UTF-8 continuation byte
  • Merge two columns in Pandas
  • Side Effect error in Python in an online compiler
  • How to convert a navigation list with depth levels to a parent-child flat list?
  • Retrieving values from a paired key dictionary in Python
  • How to test the current text of a Tkinter text box widget before inserting new text after user clicks on a button?
  • computing the Cumulative Sum, where Sum can be reset by a condition
  • Where do you specify your API key when making a request with the Google API python library?
  • Pandas DataFrame, computing the Time Difference between one row and other row which satisfies a condition
  • Discord.py bot not reading other bot's messages
  • How do I write a Django query that finds words in a Postgres column?
  • Download S3 File Using Boto3
  • Retrieve status of model training after closing notebook
  • If Current Date is in Column Then Show Row
  • How do I stay in a for loop's element until a condition is met?
  • QPainter point size is 1 pixel and can not be changed
  • How to download the excel file which has no link in Beautifulsoup?
  • Can't read the content of a certain page of a pdf file available online
  • Delete all rows before the first appearance of a condition in a pandas data frame
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com