I am currently developing an app to manage apartments. One requirement is to be able to handle payment from tenants by utilizing his room/security deposit. For this case, the involve models will be as follows (minimum setup):
'''
class Billing(models.Model):
bill_batch = models.ForeignKey(BillBatch, on_delete=models.PROTECT)
reservation = models.ForeignKey(
'tenants.Reservation', on_delete=models.PROTECT)
rental = models.DecimalField(max_digits=9, decimal_places=2, default=0)
electricity = models.DecimalField(max_digits=9, decimal_places=2, default=0)
water = models.DecimalField(max_digits=9, decimal_places=2, default=0)
class SecurityDeposit(models.Model):
payments = models.ForeignKey(Payment, on_delete=models.PROTECT)
reservations = models.ForeignKey(
'tenants.Reservation', on_delete=models.PROTECT)
deposit_date = models.DateField(default=date.today,
verbose_name='Date deposited')
deposited_amount = models.DecimalField(max_digits=9, decimal_places=2,
default=0, verbose_name='Amount deposited')
class ConsumeDeposit(models.Model):
billings = models.ForeignKey(
'billings.Billing', on_delete=models.PROTECT)
security_deposits = models.ForeignKey(
SecurityDeposit, on_delete=models.PROTECT)
pay_date = models.DateField()
allocated_amount = models.DecimalField(
max_digits=9, decimal_places=2, default=0)
'''
In my code,
'''
class ConsumeDepositEditMixin(object):
def dispatch(self, request, *args, **kwargs):
self.security_deposit = get_object_or_404(
SecurityDeposit, id=self.kwargs['deposit_id'])
# the qs must contain only billings exclusive to the reservation
# by which the deposit is allocated for; that is, deposit can't be consumed
# by other room reservations of the same tenant
self.billing_qs = Billing.objects.filter(
reservation=self.security_deposit.reservations)
# TODO: need fix, can't change billing item
return super().dispatch(request, *args, **kwargs)
def get_form(self, form_class=None):
form = super().get_form(form_class=None)
form.fields['security_deposits'].widget = forms.HiddenInput()
form.fields['billings'].queryset = self.billing_qs
return form
'''
In the tests I made, I have 2 billings available, say Billing-July and Billing-August for a reservation, say Reservation-1. The problem is, when I tried to change the billing instance, the saving process will finish without error but when I open back the ConsumeDeposit form, the change was not saved. I tried to remove the filter in the self.billings_qs, and it worked just fine.
I also tried to change the queryset to this,
'''
reservations = Reservation.objects.filter(id=self.security_deposit.reservations_id)
self.billing_qs = Billing.objects.filter(
reservation_id__in=Subquery(reservations.values('id')))
'''
But the same result. What corrections should I make in order to make this work?