The problem is that with this approach, annotate ignores equal amounts, and if you remove distinct=True, then there will be duplicate objects and the difference will not be correct.
In simple words, I want to get the balance of the account by getting the difference between the amount in cash and the amount on receipts for this personal account
queryset = PersonalAccount.objects.select_related(
'apartment', 'apartment__house', 'apartment__section', 'apartment__owner',
).annotate(
balance=
Greatest(Sum('cash_account__sum', filter=Q(cash_account__status=True), distinct=True), Decimal(0))
-
Greatest(Sum('receipt_account__sum', filter=Q(receipt_account__status=True), distinct=True), Decimal(0))
).order_by('-id')
class PersonalAccount(models.Model):
objects = None
class AccountStatus(models.TextChoices):
ACTIVE = 'active', _("Активен")
INACTIVE = 'inactive', _("Неактивен")
number = models.CharField(max_length=11, unique=True)
status = models.CharField(max_length=8, choices=AccountStatus.choices, default=AccountStatus.ACTIVE)
apartment = models.OneToOneField('Apartment', null=True, blank=True, on_delete=models.SET_NULL,
related_name='account_apartment')
class CashBox(models.Model):
objects = None
number = models.CharField(max_length=64, unique=True)
date = models.DateField(default=datetime.date.today)
status = models.BooleanField(default=True)
type = models.BooleanField(default=True)
sum = models.DecimalField(max_digits=10, decimal_places=2)
comment = models.TextField(blank=True)
payment_items = models.ForeignKey('PaymentItems', blank=True, null=True, on_delete=models.SET_NULL)
owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, related_name='owner')
manager = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='manager')
personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True,
on_delete=models.SET_NULL, related_name='cash_account')
receipt = models.ForeignKey('Receipt', blank=True, null=True, on_delete=models.SET_NULL)
class Receipt(models.Model):
objects = None
class PayStatus(models.TextChoices):
PAID = 'paid', _("Оплачена")
PARTIALLY_PAID = 'partially_paid', _("Частично оплачена")
NOT_PAID = 'not_paid', _("Не оплачена")
number = models.CharField(max_length=64, unique=True)
date = models.DateField(default=datetime.date.today)
date_start = models.DateField(default=datetime.date.today)
date_end = models.DateField(default=datetime.date.today)
status = models.BooleanField(default=True)
status_pay = models.CharField(max_length=15, choices=PayStatus.choices, default=PayStatus.NOT_PAID)
sum = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, blank=True)
personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True,
on_delete=models.CASCADE, related_name='receipt_account')
tariff = models.ForeignKey('Tariff', null=True, on_delete=models.CASCADE)
apartment = models.ForeignKey('Apartment', null=True, on_delete=models.CASCADE,
related_name='receipt_apartment')
Related
_Hi, guys! I'm trying to sum times for users for each Month(Mission), like this:
times = goal.time_set.filter(day__year=today.year, day__month=today.month)
Then I will sum:
for time in times:
total_min[member_number] = total_min[member_number] + time.value
But it calculates for current Month(Mission).
I want to calculate time depends on object model Mission. Model Mission:
class Mission(models.Model):
name = models.CharField(max_length=200, default='')
description = models.TextField(default='')
add_info = models.TextField(default='', blank=True)
theme = models.ImageField(upload_to='themes/', default='themes/default.png')
date_created = models.DateTimeField(null=True)
date_finished = models.DateTimeField(null=True, blank=True)
Like this I think:
times = goal.time_set.filter(day__year=mission.date_created.year, day__month=mission.month_created.month)
How can I achieve it?
upd. Goal model:
class Goal(models.Model):
STATUS = (
('in progress', 'in progress'),
('completed', 'completed'),
('failed', 'failed')
)
id_ninja = models.ForeignKey(Ninja, null=True, on_delete=models.SET_NULL)
id_user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
name = models.CharField(max_length=150, default='')
description = models.TextField(default='')
date_created = models.DateTimeField(null=True)
status = models.CharField(max_length=20, choices=STATUS, default='in progress')
I solved the problem in my way.
mission_year = mission.date_created.strftime('%Y')
mission_month = mission.date_created.strftime('%m')
times = goal.time_set.filter(day__year__gte=mission_year, day__month__gte=mission_month)
I want to make pay form, but I cannot show produk in orederitem, please helping me to show orderitem :v. I am really newbie in here .
models.py
class Order(models.Model):
name = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True)
order_data = models.DateTimeField(auto_now_add=True)
selesai = models.BooleanField(default=False, blank=True, null=True)
status = models.BooleanField(default=False, blank=True, null=True)
id_transaksi = models.CharField(max_length=200, null=True)
bukti = models.ImageField(null=True, blank=True)
ongkir = models.CharField(max_length=200, null=True)
total = models.CharField(max_length=200, null=True)
total_harga = models.CharField(max_length=200, null=True)
pembayaran = models.CharField(max_length=200, null=True)
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.IntegerField(default=0)
date_added = models.DateTimeField(auto_now_add=True)
views.py
def pembayaran(request):
customer = request.user.profile
ido = Order.objects.filter(id)
orders = Order.objects.filter(name=customer, selesai=True)
pengiriman = Pengiriman.objects.filter(name=customer)
OrderItems = OrderItem.objects.filter(order=ido)
print(OrderItems)
context = {'orders': orders,'pengiriman' :pengiriman , 'OrderItems': OrderItems }
return render(request, 'store/pembayaran.html', context)
I need to have multiple editable rows Header and Items of products and variants of products in Django Admin change_list.html / change_list_results.html like the image below:
Example result
this is my model:
class VariantProduct(models.Model):
product = models.ForeignKey(Product, verbose_name=_('Prodotto'), related_name='variants', on_delete=models.CASCADE)
sku = models.CharField(_('SKU'), max_length=40, blank=True, null=True,
help_text='SKU', unique=True)
ean_13 = models.BigIntegerField('EAN 13',
validators=[MaxValueValidator(9999999999999, "Ammessi massimo 13 numeri.")],
blank=True, null=True, help_text='Codice numerico EAN 13')
ean_128 = models.CharField('EAN-128', max_length=128, blank=True, null=True,
help_text='Codice alfanumerico 128')
qr_code = models.CharField("Codice QR", blank=True, null=True, max_length=255,
help_text="digitare il codice per la generazione del QR Code")
barcode = models.ImageField('Barcode', upload_to='barcode/', blank=True, null=True)
quantity = models.IntegerField('Quantità', blank=True, null=True)
class Meta:
verbose_name = _('prodotto')
verbose_name_plural = _("prodotti")
ordering = ['name']
class VariantProduct(models.Model):
product = models.ForeignKey(Product, verbose_name=_('Prodotto'), related_name='variants', on_delete=models.CASCADE)
sku = models.CharField(_('SKU'), max_length=40, blank=True, null=True,
help_text='SKU', unique=True)
ean_13 = models.BigIntegerField('EAN 13',
validators=[MaxValueValidator(9999999999999, "Ammessi massimo 13 numeri.")],
blank=True, null=True, help_text='Codice numerico EAN 13')
ean_128 = models.CharField('EAN-128', max_length=128, blank=True, null=True,
help_text='Codice alfanumerico 128')
qr_code = models.CharField("Codice QR", blank=True, null=True, max_length=255,
help_text="digitare il codice per la generazione del QR Code")
barcode = models.ImageField('Barcode', upload_to='barcode/', blank=True, null=True)
quantity = models.IntegerField('Quantità', blank=True, null=True)
qta_stock_add = models.PositiveSmallIntegerField('Q.ta +', help_text='Diminuisci N. Prodotti', blank=True,
null=True, )
qta_stock_sub = models.PositiveSmallIntegerField('Q.ta -', help_text='Diminuisci N. Prodotti', blank=True,
null=True, )
minimal_quantity = models.IntegerField('Scorta Minima', blank=True, null=True,
help_text='Scorta minima di magazzino, può essere negativa per gestione sotttottoscorta')
image = models.ImageField(upload_to='prodotti/%Y/%m/%d',
verbose_name=_('Immagine Variante'), blank=True, null=True)
state = models.BooleanField('Attivo', help_text='Stato della variante prodotto attivo/disattivo', default=True)
price = models.DecimalField(_('Prezzo'), max_digits=8, decimal_places=2, default=0.00)
dealer_price = models.DecimalField(_('Prezzo Rivenditore'), max_digits=8, decimal_places=2, default=0.00)
size = models.ForeignKey(Size, verbose_name=_('Taglia'), blank=True, null=True, on_delete=models.PROTECT)
color = models.ForeignKey(Color, verbose_name=_('colore'), blank=True, null=True, on_delete=models.PROTECT)
weight = models.DecimalField(_('Peso gr.'), blank=True, null=True, decimal_places=2, max_digits=10,
help_text=_('Peso in grammi'))
height = models.IntegerField(_('Altezza cm'), blank=True, null=True,
help_text=_('Altezza in grammi'))
width = models.IntegerField(_('Larghezza cm'), blank=True, null=True,
help_text=_('Larghezza in grammi'))
length = models.IntegerField(_('Lunghezza cm'), blank=True, null=True,
help_text=_('Lunghezza in grammi'))
class Meta:
verbose_name = _('Variante Prodotto')
verbose_name_plural = _('Varianti Prodotto')
def __str__(self):
return '{cod} - {name}'.format(cod=self.sku, name=self.product.name)
Is possible to show on django admin page the row of a product an relative rows of variants and make editable the fields of "quantity" on all rows?
Thanks in advance.
W.
i have this order model:
class Order(models.Model):
productType = [
('Document', 'Document'),
('Parcel', 'Parcel'),
('Box', 'Box')
]
serviceType = [
('Home', 'Home delivery'),
('Office', 'Office delivery'),
('Pick up from office', 'Pick up from office'),
]
delivery_StatusType = [
('Return', 'Return'),
('Delivering', 'Delivering'),
('Pending', 'Pending'),
('Complete', 'Complete')
]
statustype = [
('Paid', 'Paid'),
('Cash on delivery', 'Cash on delivery')
]
status = [
('Instant', 'Instant'),
('Same Day', 'Same Day'),
('Others', 'Others')
]
payment_types = [
('Cash', 'Cash'),
('Wallet', 'Wallet'),
('Online', 'Online')
]
CHOICE_AREA = [
('Inside Dhaka', 'Inside Dhaka'),
('Dhaka Suburb', 'Dhaka Suburb'),
('Outside Dhaka', 'Outside Dhaka')
]
user = models.ForeignKey(User, on_delete=models.CASCADE)
receiver = models.CharField(max_length=100, blank=False, unique=False)
receiver_Contact = models.CharField(
max_length=20, blank=False, unique=False)
receiver_Email = models.CharField(
max_length=100, blank=False, unique=False)
payment = models.CharField(
max_length=100, choices=payment_types, blank=False)
area = models.CharField(
max_length=100, choices=CHOICE_AREA, blank=True, null=True)
weight = models.CharField(max_length=100, blank=True, null=True)
service = models.CharField(choices=serviceType, max_length=100)
product_Type = models.CharField(choices=productType, max_length=100)
contents = models.CharField(max_length=100, blank=False, unique=False)
quantity = models.CharField(max_length=100, blank=False, unique=False)
package = models.ForeignKey(
Package, on_delete=models.CASCADE, default=0)
priority = models.CharField(
choices=status, blank=True, null=True, max_length=20)
amount = models.CharField(max_length=100, blank=True, unique=False)
delivery_Status = models.CharField(
choices=delivery_StatusType, blank=True, null=True, max_length=50)
paid = models.BooleanField(default=False)
reference_id = models.CharField(max_length=100, blank=True, unique=True)
delivery_time = models.DateField(blank=True, null=True)
created = models.DateField(auto_now_add=True)
tran_id = models.CharField(max_length=20, blank=True, null=True)
driver = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='driver', blank=True, null=True)
driver_amount = models.CharField(max_length=5, blank=False, default='0')
delivery_now = models.DateField(auto_now_add=True)
delivery_later = models.DateField(blank=True, null=True)
accept = models.BooleanField(default=False)
start = models.BooleanField(blank=True, null=True)
finish = models.BooleanField(blank=True, null=True)
pick_up_latitude = models.CharField(blank=True, null=True, max_length=50)
pick_up_longitude = models.CharField(blank=True, null=True, max_length=50)
delivery_latitude = models.CharField(blank=True, null=True, max_length=50)
delivery_longitude = models.CharField(blank=True, null=True, max_length=50)
otp = models.CharField(max_length=10, blank=True, null=True)
pickup_finish = models.BooleanField(default=False)
approve_change_delivery_address = models.BooleanField(
blank=True, null=True, default=False)
confirm_change_delivery_address = models.BooleanField(
blank=True, null=True, default=False)
def __str__(self):
return self.user.username
user model:
class User(AbstractUser):
CITIES = [
('Dhaka','Dhaka'),
('Rajshahi','Rajshahi'),
('Chittagong','Chittagong'),
('Sylhet','Sylhet'),
('Khulna','Khulna'),
('Mymensingh','Mymensingh'),
('Rangpur','Rangpur'),
('Dinajpur','Dinajpur'),
]
Vehicle_type = [
('Truck','Truck'),
('Van','Van'),
('Bike','Bike')
]
email = models.EmailField(unique=True)
contact = models.CharField(null=False,blank=False,max_length=20)
contact2 = models.CharField(null=True,blank=True,max_length=20)
contact3 = models.CharField(null=True,blank=True,max_length=20)
contact4 = models.CharField(null=True,blank=True,max_length=20)
address = models.CharField(null=False,blank=False,max_length=100)
address2 = models.CharField(null=True,blank=True,max_length=100)
postal_code = models.CharField(null=True,blank=True,max_length=10)
city = models.CharField(max_length=30,choices=CITIES)
username = models.CharField(max_length=200,unique=True)
user_pic = models.ImageField(upload_to='media/images/')
n_id = models.CharField(max_length=100)
quote = models.CharField(max_length=250,blank=True,null=True,default='Bio Here. . .')
driving_license = models.ImageField(upload_to='media/documents/')
vehicle_type = models.CharField(max_length=30,choices=Vehicle_type)
vehicle_no = models.CharField(max_length=50)
latitude = models.CharField(max_length=100,default=0)
longitude = models.CharField(max_length=100,default=0)
is_driver = models.BooleanField(default=False)
is_delivery_man = models.BooleanField(default=False)
is_merchant = models.BooleanField(default=False)
is_agent = models.BooleanField(default=False)
is_user = models.BooleanField(default=False)
is_available = models.BooleanField(default=False)
def __str__(self):
return self.username
now the problem is i want to show the username , total amount collections and total orders by individual users(is_agent).no name will be repeated twice though the queryset can have multiple orders agains a user.
i just want to show a users orders total amount and total deliveries in a table row,then other row will be for other users. N.B.filtering (delivery_status="Complete")
update:
agents = User.objects.filter(is_active=True,is_agent=True)
for agent in agents:
agent_id = agent.id
all_orders = Order.objects.filter(user_id = agent_id, delivery_Status="Pending", delivery_time__month = date,
delivery_time__year = year)
now in here i want every agents total delivery count and total amount collected from them but not like showing same user's all querysets but instead i want only by his name will appear once in the table and all deliveries total amount and total deliveries into that row just like the given table
itried this but this has no track of which collection is for whom
individual_orders = []
final_list = []
grand_final_list = []
order_amount = []
individual_orders_count = []
agents = User.objects.filter(is_active=True,is_agent=True)
for agent in agents:
agent_id = agent.id
all_orders = Order.objects.filter(user_id = agent_id, delivery_Status="Pending", delivery_time__month = date,
delivery_time__year = year)
if all_orders:
individual_orders.append(all_orders)
individual_orders_count.append(len(all_orders))
cash_collection = Order.objects.filter(user_id = agent_id, delivery_Status="Pending", delivery_time__month = date,
delivery_time__year = year).values('amount').aggregate(Sum('amount'))
for k,v in cash_collection.items():
if v:
order_amount.append(v)
for query in individual_orders:
for entry in query:
final_list.append(entry.user.username)
grand_final_list = list(dict.fromkeys(final_list))
this table
maybe this helps you?
all_orders = Order.objects.filter(user_id = agent_id, delivery_Status="Pending", delivery_time__month = date,
delivery_time__year = year).values(id, username=F(user__username)).annotate(total_amount = Sum('amount')).annotate(total_deliveries = Count('id))
finally i found a way i am showing the demo here
def driver_deliveries(request):
name = {}
data = []
count = Order.objects.filter(driver__is_driver=True).distinct()
for i in count:
query = Order.objects.filter(driver_id=i.driver.id,delivery_Status="Complete").count()
name[i.driver.username] = data
data.append(query)
data = []
print(name)
for k,v in name.items():
print(k)
for i in v:
print(i)
return render(request,'user/driver_deliveries.html',{'name': name})
I want to filter my queryset if and only if loan exists in my model ShgGroupLoanMarking.
class ShgGroupLoanMarking(models.Model):
shg = models.ForeignKey(Shg, null=True)
category = models.CharField(max_length=25, choices=GROUP_CATEGORY, default="shg_group")
msss = models.ForeignKey(Msss, null=True)
shgmember = models.ForeignKey(ShgMember, null=True)
loan = models.ForeignKey(Loan, null=True)
date_of_marking = models.DateField(null=True)
paid = models.CharField(max_length=100, null=True)
loan_amount = models.CharField(max_length=100, null=True)
service_charge = models.CharField(max_length=100, null=True)
description = models.CharField(max_length=100, null=True)
status = models.CharField(max_length=100, null=True)
print_status = models.BooleanField(default=False)
sent_to_bank_status = models.BooleanField(default=False)
receipt_number = models.IntegerField(default=0)
How do I implement this?
ShgGroupLoanMarking.objects.filter(loan__isnull=False)
or
ShgGroupLoanMarking.objects.exclude(loan=None)