Saturday, October 27, 2018

Django admin model calc something before save to db

#models.py
'''orderMain'''
class OrderMain(models.Model):
    orderId = models.UUIDField(primary_key=True, max_length=30)#sum(OrderDetail.amount)
    sumAmount = models.DecimalField(max_digits=13,decimal_places=3,null=True) #sum(orderDetail.amount)

    class Meta:
        db_table = 'orderMain'
 

    def __str__(self):
        return self.orderId

    def save(self, *args, **kwargs):
        super(OrderMain, self).save(*args, **kwargs)

'''orderDetail'''
class OrderDetail(models.Model):
    orderId = models.ForeignKey(OrderMain,to_field='orderId',db_column='orderId',on_delete=models.CASCADE)
    amount = models.DecimalField(max_digits=8,decimal_places=2)

    class Meta:
        db_table = 'orderDetail'

    def __str__(self):
        return ''

#admin.py
class OrderDetailInLine(admin.TabularInline):
    model = OrderDetail
    extra = 1

@admin.register(OrderMain)
class OrderMainAdmin(admin.ModelAdmin):
    inlines = [OrderDetailInLine,]
    list_display = ['orderId','sumAmount']
    readonly_fields = ['orderId','sumAmount']
    fields = ('orderId', 'sumAmount')



#Questions: Can I calc orderMain.sumAmount = sum(orderDetail.amount)  before objects save to db?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/aab92d88-b78b-460e-bf8b-c89ea0de86b8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment