I have a model in my django web app and I have been trying to query the model in such a way that I can sum up values in the quantity column. I already have data in this model so I just need to add up all the values in the quantity column.
class ProductInstance(models.Model):
product=models.ForeignKey(Product,on_delete=models.RESTRICT,related_name='product')
quantity=models.IntegerField()
warehouse=models.ForeignKey(Warehouse,on_delete=models.RESTRICT,related_name='warehouse')
I tried "ProductInstance.objects.sum(quantity)". It didnt work
You can use aggregate functions for this kind of cases.
from django.models import Sum
ProductInstance.objects.all().aggregate(sum=Sum('quantity'))
Related
TAssignment model has many entries related to TSlot model like for 1 pk of TSlot model there are many entries in TAssignment model.Now this queries outputs values from Tslot table and also latest related created on and updated on from Tassignment table.But what i want is latest value of
'assignment_Slot__created_on' and 'assignment_Slot__updated_on' when assignment_Slot__is_deleted=False.
QUESTION: How to add "assignment_Slot__is_deleted=False" condition along with 'assignment_Slot__created_on' and 'assignment_Slot__updated_on' inside annotate without duplicating results.
** assignment_Slot here is related name
TSlot.objects.filter(request__id=request_id, is_deleted=False
).values("slot_date", "type_of_work", "reason_for_less_assign", "request_id","slot", "remarks",
slot_id=F("id"), request_status=F('request__request_status')).annotate(
assigned_on=Max('assignment_Slot__created_on'), modified_on =Max('assignment_Slot__modified_on'))
Add a filter to your annotations, see filtering on annotations
from django.db.models import Max, Q, DateField
TSlot.objects.filter(...).annotate(
assigned_on=Max('assignment_Slot__created_on', filter=Q(assignment_Slot__is_deleted=False), output_field=DateField()),
modified_on=Max('assignment_Slot__modified_on', filter=Q(assignment_Slot__is_deleted=False), output_field=DateField())
)
Looking for an efficient way to sum a list of attributes using ndb queries. Currently I just fetch the results and run a for loop over them.
class Player(ndb.Model):
score = ndb.IntegerProperty()
score_of_group = 0
all_players = Player.query().filter("various filters").fetch()
for player in all_players:
score_of_group += player.score
If that's the model (a single model) you have and your '''various filters' are just different ways to filter that single model, I don't believe you can sum directly in the queries.
For the Python code itself, you can use the inbuilt sum function and so your code could be something like
all_players = Player.query().filter("various filters").fetch()
score_of_group = sum([x.score for x in all_players])
If you happen to have at least 2 models and you are fetching records from another model based on the value in another model (e.g. you have a list of people and you need to retrieve all their plays/scores from another table), then you should look at #ndb.tasklet to speed up the data retrieval/make it more efficient but you would still have to sum it yourself
I am kinda new in django and I am stuck.
I am building and app to store equipment registry. I have done a model for equipment list and i have a status values as "available", "booked", "maintenance"
I also have a model for all equipment that are not available. not in my html in the "not available registry" i want to show only details of equipment in the list that are marked as "booked" and "maintenance"
There are three ways of doing this.
To filter out objects of the model that are marked as "booked" or "maintenance" you can use complex lookups with Q objects. It allows you to filter objects with OR statement. Here you need to find objects that have status set to "booked" OR to "maintenance". The query should look like this:
from django.db.models import Q
Equipment.objects.filter(Q(status='booked') | Q(status='maintetnance'))
Second way of doing this is by using __in statement to filter objects that you need:
not_available_status = ['booked', 'maintenance']
Equipment.objects.filter(status__in=not_available_status)
And final way is to exclude objects that you don't need:
Equipment.objects.exclude(status='available')
I am trying to create a cart using django-carton App. I have two models: Halls and Caterer. I want to add either of these Halls or Caterer object in cart when I will call add() method. While using this API, I need to register my model in settings.py as below
CART_PRODUCT_MODEL = 'marriage_halls.models.Hall'
I can register only one model at a time. So I can't add Caterer object in the cart.To resolve this issue, I'm planning to create new 'product' model which will contain 3 columns viz. {name, price, city}. These are the columns which are common in both Hall and Caterer and I want to display them when I'll call show() method. My first question is, is it a correct way to do it?
If its a correct approach, What I want to do is, whenever I will add new Hall or Caterer in their respective tables through Django's admin interface, only these 3 column values should get inserted to Product table (INSERT new row in product table).
How can I achieve this?
Make Product a base class and use multi table inheritance.
https://docs.djangoproject.com/en/1.10/topics/db/models/#multi-table-inheritance
I have model with following field.
date = models.DateTimeField(auto_now_add=True)
When querying such model i`d like to have additional column that would keep difference between current date and previous one. So for 10 rows it would have 9 values, first one would be None. Are there any ways of achieving this with querysets? or maybe i should mess around and create additional list that would hold such differences before i pass queryset to template?
Please advise.
Create a property on the model that calls get_ {next,previous}_ by_*() and returns the timedelta. For advanced functionality, implement caching.