I want to retrieve all the value from a field having same foreign key value , then I have to add those values and display it in the response.
status = models.CharField(
max_length=50,
choices=WALLET_STATUS_CHOICES,
default='cash')
merchant = models.ForeignKey(
merchant_models.Merchant,
db_index=True,
on_delete=models.CASCADE,
related_name='merchant12',
null=True,
blank=True)
cheque_no = models.CharField(
max_length=100,
null=True,
blank=True)
cheque_date= models.DateTimeField()
recharge_amount=models.FloatField(null=True, blank=True, default=0.0)
def __unicode__(self):
return str(self.name)
I have to get all the recharge values having same merchant id then I have to add those value and have to display.i have to get this sum in "merchant/id " url.is there any way in django?
Let suppose your model name is EXA and merchant_id is the id of merchant,then.
merchant_obj = Merchant.objects.get(id=merchant_id)
objects = EXA.objects.filter(merchant=merchant_obj)
total_recharge = 0
for object in objects:
total_recharge += object.recharge_amount
print total_recharge
Or you can use aggregate
from django.db.models import Sum
merchant_obj = Merchant.objects.get(id=merchant_id)
total_recharge = EXA.objects.filter(merchant=merchant_obj).aggregate(Sum('recharge_amount'))
print total_recharge
Assuming your model name is Transaction.
If you have access to the merchant object somewhere in your logic:
qs = Transaction.objects.filter(merchant=merchant)
Or if you know the foreign key id for the merchant_id:
qs = Transaction.objects.filter(merchant_id=merchant_id)
Then you can use the aggregate and Sum function in Django:
from django.db.models import Sum
qs.aggregate(Sum('recharge_amount'))
OR all in line:
from django.db.models import Sum
total_recharge = Transaction.objects.filter(
merchant_id=merchant_id
).aggregate(
Sum('recharge_amount'))
Related
I have problems with the following queryset, I probe it in django shell and it returns an empty list.
The situation is that I'm occupying a lforeing key, I did the same exercise with the model "Tarifa_Sem" and returns the value without any problem, just replace the F ('') by a variable x = 1000
The situation is that the table of the model "Tarifa_Sem" is only for consultation.
Where I am going to manage and save the response of the queryset is in the "Calculadora_isr" model
Model 1
class Tarifa_Sem(models.Model):
limite_inferior_isr = models.DecimalField(max_digits=10, decimal_places=2)
limite_inferior_subsidio = models.DecimalField(max_digits=10, decimal_places=2)
limite_superior = models.DecimalField(max_digits=10, decimal_places=2)
Model 2
class Calculadora_isr(models.Model):
tarifa = models.ForeignKey(Tarifa_Sem, on_delete=models.CASCADE, blank=True)
base_gravada = models.DecimalField(max_digits=10, decimal_places=2, blank=True)
limite_inf_calculo = models.DecimalField(max_digits=10, decimal_places=2, blank=True)
Queryset and save()
def limite_inferior(self):
queryset = Calculadora_isr.objects.filter(tarifa__limite_superior__gte=F('base_gravada'),tarifa__limite_inferior_isr__lte=F('base_gravada')).distinct().values('tarifa__limite_inferior_isr')
return queryset
def save(self):
self.limite_inf_calculo = self.limite_inferior
super (Calculadora_isr, self).save()
In the shell of django the list appears empty.
>>> queryset = Calculadora_isr.objects.filter(tarifa__limite_superior__gte=F('base_gravada'),tarifa__limite_inferior_isr__lte=F('base_gravada')).distinct().values('tarifa__limite_inferior_isr')
And in the admin when I give him save he tells me:
conversion from method to Decimal is not supported
thanks for the support
I finally found the solution.
To solve the problem of passing the "base_gravada" field, use another variable that returns all the values of "base_gravada"
qs1 = Calculadora_isr.objects.values_list('base_gravada')
And in my second query, use the variable qs1:
qs2 = Tarifa_Sem.objects.filter(limite_superior__gte=qs1,limite_inferior_isr__lte=qs1).distinct().values('limite_inferior_isr')
I'm stumped. I have a Django query that should return results, but does not seem to.
I have a database with a model Postcodes with latitude and longitude data.
class Postcode(models.Model):
name = models.CharField(max_length=50)
postcode = models.CharField(max_length=7)
latitude = models.DecimalField(max_digits=8, decimal_places=5, blank=True, null=True)
longitude = models.DecimalField(max_digits=8, decimal_places=5, blank=True, null=True)
I want to find the postcodes with 100km of a given postcode, at:
{'latitude': 1.445671659052796, 'longitude': 1.6673342919117797}
and I find the latitude and longitude ranges to be:
longitude_max = 1.9703812919117922
longitude_min = -1.3642872919117792
latitude_max = 52.2326886590528
latitude_min = 49.3413453409472
I query the db like so:
return Postcode.objects.filter(latitude__range=(latitude_min, latitude_max), longitude__range=(longitude_min, longitude_max))
But I don't get anything back? I should at least get the result I extrapolated the ranges from!
If you are filtering with those parameters for that coordinate, the queryset will not contain that item. The latitude is outside of the range provided.
class SaleAdvancePaymentInv(models.TransientModel):
_inherit = "sale.advance.payment.inv"
#api.multi
def _create_invoice(self, order, so_line, amount):
inv_obj = super(SaleAdvancePaymentInv, self)._create_invoice(order, so_line, amount)
inv_obj.write({'service_id':order.service_id.id})
This is my code.service id does not pass sale order to invoice through invoiceable lines.
But when I use downpayment the service id is passed to invoice.
*What is the reason behind this.?
How to pass the values through the invoiceable line?*
#api.multi
def _prepare_invoice(self):
dict_obj = super(SaleOrder, self)._prepare_invoice()
dict_obj.update({'service_id': self.service_id.id})
I override the prepare invoice function update the service value in dictionary
I would like to combine 2 querysets from 2 differents models, then I need to order them by date and finally my goal is to serialize it.
So far I did that :
last_actions = serializers.SerializerMethodField()
def get_last_actions(self, obj):
prc = obj.product_request_configs.all().order_by('modified_date')[:5]
psc = obj.product_send_configs.all().order_by('modified_date')[:5]
result_list = sorted(
chain(prc, psc),
key=attrgetter('modified_date'),
reverse=True)
But I don't know how to call my two django rest serializers so that I can return the right data.
If I could make a database view it coult be simpler I think.
Serializers are designed for match one model relationship, so we need to create a custom Model for the logic you are trying to achieve:
class CustomModel(models.Model):
def dictfetchall(self, cursor):
"""Returns all rows from a cursor as a dict"""
desc = cursor.description
return [dict(zip([col[0] for col in desc], row))
for row in cursor.fetchall()]
def yourMethod(self):
cursor = connection.cursor()
cursor.execute("""
select field1, field2 from app_table
where field1=%s and field2=%s group by field1
""",
[value1, value2,]
)
return self.dictfetchall(cursor)
class Meta:
abstract = True
This will return a dictionary and then you can serialize that response with a seializer like:
class CustomModelSerializer(serializers.Serializer):
field1 = serializers.IntegerField()
field2 = serializers.CharField()
Please note that on SQL you can use as keyword to rename some fields, the current name of fields must match var names in your serializer.
I'm trying to use the mptt library for a simple nested comment system.
My Model
class Comment(MPTTModel):
event = models.ForeignKey(Event)
author = models.CharField(max_length=60)
comment = models.TextField()
added = models.DateTimeField(default=timezone.now())
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
class MPTTMeta:order_insertion_by = ['added']
Right now, if I use {% recursetree nodes %} template tag, it displays the nodes in ascending time based on 'added'. I want to display the root notes by descending time, the newest comments first. I tried sorting nodes so it is descending, but recursetree does not follow that order. Is there a way to specify a descending ordering? I tried ['-added'], but it does not work.
Download updated version of django-mptt from github - It will allow you to use descending order the way you wanted. For example:
class Comment(MPTTModel):
event = models.ForeignKey(Event)
author = models.CharField(max_length=60)
comment = models.TextField()
added = models.DateTimeField(default=timezone.now())
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
class MPTTMeta:
order_insertion_by = ['-added']