## Floor Division and Modulo in ListView Django

With Django Listview, is it possible to display new columns that contain the values of floor division and modulo?

I have the following two models:

##### models.py

class Model_Item(models.Model): item_name = models.CharField(max_length = 100, null = False, blank = False, unique = True) item_bottleperpack = models.FloatField(null = True, blank = False) # e.g. 100 bottles per pack def __unicode__(self): return self.item_name class Model_ItemTransaction(models.Model): item = models.ForeignKey(Model_Item, to_field = "item_name") item_sold = models.FloatField(null = True, blank = True) # in terms of bottle def __unicode__(self): return self.item

With this listview:

##### views.py

class View_Item(ListView): def get_queryset(self): queryset = Model_Item.objects.all() queryset = queryset.annotate( sum_ = Sum("model_itemtransaction__item_sold") ) queryset = queryset.annotate( floor_division_ = F("sum_") // F("item_bottleperpack"), module_ = F("sum_") %% F("item_bottleperpack") ) return queryset

Basically, if I have sold, say 650 bottles, and there is 100 bottles per pack, I would like the listview to display:

**6**packs on the "floor-division" column, and**50**bottles on the "modulo" column.

Currently I am receiving the following errors with my current code

unsupported operand type(s) for //: 'F' and 'F' and unsupported operand type(s) for %%: 'F' and 'F'

and hoping someone could help me find any solution to this (and it does not have to be with conditional expression).

According to https://docs.djangoproject.com/en/2.0/_modules/django/db/models/expressions/:

Neither class `F`

nor it's parent `Combinable`

implement `__floordiv__`

, so `//`

is not implemented. `Combinable`

does implement `__truediv__`

, which is the `/`

operator.

I haven't heard of the operator `%%`

in Python, but `%`

will work because `__mod__`

is implemented in `Combinable`

.

Try using `models.IntegerField`

or `models.PositiveIntegerField`

for `item_bottleperpack`

and `item_sold`

, and updating this line in views.py:

queryset = queryset.annotate( floor_division_ = F("sum_") / F("item_bottleperpack"), module_ = F("sum_") % F("item_bottleperpack") )

I'm assuming that Combinable will return an integer as the output of dividing two integers -- this might not be the case. If so, you might want to round down the result.

**NoReverseMatch at /restaurant/meal/9/edit/ at Django,** According to https://docs.djangoproject.com/en/2.0/_modules/django/db/models/expressions/: Neither class F nor it's parent Combinable implement __floordiv__ Floor division. Floor division is also used to carry out Euclidean division, but unlike the modulo operator, floor division yields the quotient, not the remainder. Let's look at a couple of examples: >>> 10 // 3 3 >>> 9 // 2 4 We can create a small function to print out the full result of Euclidean division like so:

So I have found a way to solve this, thanks to this post.

First I cleaned the code at views.py,

##### views.py

class View_Item(ListView): def get_queryset(self): queryset = Model_Item.objects.all() queryset = queryset.annotate( sum_ = Sum("model_itemtransaction__item_sold") ) return queryset

then added this code file into the templatetags folder,

##### app_filters.py

from django import template register = template.Library() @register.filter(name = "func_floor_division") def func_floor_division(num, val): if num: floor_division = num // val return floor_division else: return None @register.filter(name = "func_modulo") def func_modulo(num, val): if num: modulo = num % val return modulo else: return None

and finally modified the tags in the html file.

##### html

{% load app_filters %} <table> <tr> <th>Floor Division</th> <th>Modulo</th> </tr> {% for obj_ in object_list %} <tr> <td>{{ obj_.sum_|func_floor_division:obj_.item_bottleperpack }}</td> <td>{{ obj_.sum_|func_modulo:obj_.item_bottleperpack }}</td> </tr> {% endfor %} </table>

Hope this helps for anyone who is encountering the same issue.

**The Django admin site | Django documentation,** With Django Listview, is it possible to display new columns that contain the values of floor division and modulo? I have the following two floor () method in Python returns floor of x i.e., the largest integer not greater than x. Syntax: import math math.floor (x) Parameter: x-numeric expression. Returns: largest integer not greater than x. Below is the Python implementation of floor () method: # Python program to demonstrate the use of floor () method. # This will import math module.

you can create a new floor_division and module_ fields in your Model_Item, then you use the post save receiver to update the floor_division and module_ fields

from django.db.models.signals import pre_save class Model_Item(models.Model): item_name = models.CharField(max_length = 100, null = False, blank = False, unique = True) item_bottleperpack = models.FloatField(null = True, blank = False) # e.g. 100 bottles per pack floor_division = models.IntegerField(null=True, blank=True) module_ = models.IntegerField(null=True, blank=True) def __unicode__(self): return self.item_name def model_item_pre_save(sender, instance, created): item = Model_Item.objects.get(id=instance.id) item_transaction = Model_Transaction.objects.get(item_id=instance.id) item.floor_division = item_transaction.item_sold // item.item_bottleperpack item.module_ = item_transaction.item_sold %% item.item_bottleperpack pre_save.connect(model_item_pre_save, sender=Model_Item)

**Django list object,** This function attempts to import an admin module in each installed application. The admin now preserves filters on the list view after creating, editing or deleting For example, you might wish to search by an integer field, or use an external tool Because of the modular design of the admin templates, it is usually neither I'm looking for a way to use something like the modulus operator in django. What I am trying to do is to add a classname to every fourth element in a loop. With modulus it would look like this: {

**Python's modulo operator and floor division,** ListView should be used when you want to present a list of objects in a html page. IntegerField is a integer number represented in Python by a int instance. of addition, subtraction, multiplication, division, modulo, and power arithmetic with In Division The number which we divide is called the dividend. The number by which we divide is called the divisor. The result obtained is called the quotient. The number left over is called the remainder. Problem Definition Create a Python program to compute Quotient and reminder of two given numbers.

**[PDF] Django Documentation,** Learn about the some less well-known operators in Python: modulo and floor division—as well as how they interact with each other and how django-mathfilters is a Python 3 module that provides different simple math filters for Django. Django provides an add template filter, but no corresponding subtracting, multiplying or dividing filters. Django ticket #361 has been closed as wontfix, so I had to create an alternative that is easy to install in a new Django project.

**Этаж и деление по модулю в ListView Django – 3 Ответа,** When Django finds a matching pattern, it calls the specified view function with an serial (PostgreSQL), or integer primary key autoincrement (SQLite) are handled for you au- In Tutorial 4 we introduced a class-based view, based on ListView: subtraction, multiplication, division, modulo, and power arithmetic with F(). One can explicitly enforce true division or floor division using native functions in the operator module: from operator import truediv, floordiv assert truediv(10, 8) == 1.25 # equivalent to `/` in Python 3 assert floordiv(10, 8) == 1 # equivalent to `//`

##### Comments

- For some reason I receive the following error when running your code "operator does not exist: double precision % double precision". Could it be because I am on Django 1.11?
- Strange. Did you change item_bottleperpack and item_sold to IntegerField in models.py? If they are still FloatField this would make sense.
- Thanks. I will try your method soon. By the way, I have found the solution and it is posted.
- It's signals in Django. It's basically used to perform a task before an object of a model is saved to the database. Others are post_save, pre_delete and so on
- Hey Bello, may I know which Django version that you are using? I tried running your code, but received a syntaxerror on "%%".