business generated has to come based on dcr(daily call report) - django

I have DCR & SalesMIS model. I want to get the business generated count. And if count is it should return the business_genrated else saleMIS.amount
I wrote a method in DCR model i.e. get_business_generated(self) and apply filter on SaleMIS model. Then trying to get the count of business_generated
ERROR:D:\Projects\Python\Django\kingllp\venv\lib\site-packages\django\db\models\base.py", line 95, in new
"INSTALLED_APPS." % (module, name)
RuntimeError: Model class builtins.DCR doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
This is DCR model
class DCR(models.Model):
STATUSES = (
('1N', 'Need Analysis'),
('2P', 'Proposal Stage'),
('3C', 'Competitive Selling'),
('4D', 'Decision Stage'),
)
prospect = models.ForeignKey(Prospect, on_delete=models.CASCADE, related_name='dcrs')
date = models.DateField(blank=True)
status = models.CharField(choices=STATUSES, max_length=2, default='1N')
discussion_points = models.CharField(max_length=2047, blank=True)
business_generated = models.IntegerField(default=0)
is_new_business = models.BooleanField(default=False)
def get_business_generated(self):
date = self.date
client = self.prospect
sale = SalesMIS.objects.filter(date=date,client = Prospect)
salecount = sale.count()
if salecount==0:
return DCR.business_generated
else:
return SalesMIS.amount
This is SaleMIS model
class SalesMIS(models.Model):
class Meta:
verbose_name_plural = _("Sale MIS")
date = models.DateField()
fls = models.ForeignKey(Employee, blank=True, null=True, on_delete=models.SET_NULL, related_name='sales')
amount = models.DecimalField(max_digits=20, decimal_places=2)
po_number = models.CharField(max_length=255, null=True, blank=True)
products = models.CharField(max_length=255, null=True, blank=True)
client = models.ForeignKey(Client, blank=True, null=True, on_delete=models.SET_NULL, related_name='client_mis')
def __str__(self):
return str(self.date) + ":" + self.fls.full_name()
Business share has to come based on DCR/MIS.

Related

Multiple try except in a serializer Django

I have a Warehouse model like the following:
class ShelfBin(models.Model):
bin_id = models.IntegerField(default=0)
bin_name = models.CharField(max_length=50, default=0)
class UnitShelf(models.Model):
shelf_id = models.IntegerField(default=0)
shelf_name = models.CharField(max_length=50, default=0)
bin = models.ManyToManyField(ShelfBin, blank=True)
class AisleUnit(models.Model):
unit_id = models.IntegerField(default=0)
unit_name = models.CharField(max_length=50, default=0)
shelf = models.ManyToManyField(UnitShelf, blank=True)
class ZoneAisle(models.Model):
aisle_id = models.IntegerField(default=0)
aisle_name = models.CharField(max_length=50, default=0)
unit = models.ManyToManyField(AisleUnit, blank=True)
class WarehouseZone(models.Model):
zone_id = models.IntegerField(default=0)
zone_name = models.CharField(max_length=50, default=0)
aisle = models.ManyToManyField(ZoneAisle, blank=True)
class Warehouse(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=250, default=0)
address = models.CharField(max_length=500, default=0)
zones = models.ManyToManyField(WarehouseZone, blank=True)
for this I have created a serializer like the following:
class WarehouseSerializer(serializers.ModelSerializer):
zones = WarehouseZonesSerializer(many=True)
class Meta:
model = Warehouse
fields = "__all__"
def create(self, validated_data):
print("validated data warehouse", validated_data)
zone_objects = validated_data.pop('zones', None)
instance = Warehouse.objects.create(**validated_data)
for item in zone_objects:
aisle_objects = item.pop('aisle')
wz_obj = WarehouseZone.objects.create(**item)
for data in aisle_objects:
unit_objects = data.pop('unit')
za_obj = ZoneAisle.objects.create(**data)
for u_data in unit_objects:
shelf_objects = u_data.pop('shelf')
au_obj = AisleUnit.objects.create(**u_data)
for s_data in shelf_objects:
bin_objects = s_data.pop('bin')
us_obj = UnitShelf.objects.create(**s_data)
for b_data in bin_objects:
b_obj = ShelfBin.objects.create(**b_data)
us_obj.bin.add(b_obj)
au_obj.shelf.add(us_obj)
za_obj.unit.add(au_obj)
wz_obj.aisle.add(za_obj)
instance.zones.add(wz_obj)
return instance
Now the problem is that sometimes warehouse can have zone, aisle, units, etc(all 5 sub-levels) but sometimes it can only be 1,2 or 0 level deep
and in that cases it raises error like this :
aisle_objects = item.pop('aisle')
KeyError: 'aisle'
So do I have to use try and except at each level of the loop or is there a better way to handle these exceptions?

Get queryset of same multiple id's of a model in django

here is my models ..
class Log(models.Model):
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
date = models.DateField(default=timezone.now, blank=True, null=True)
class Logsheet(models.Model):
log = models.ForeignKey(Log, on_delete=models.CASCADE, related_name="logsheets")
driver = models.ForeignKey(Driver, on_delete=models.CASCADE, blank=True, null=True)
trip = models.IntegerField(blank=False, null=False)
distance_from = models.FloatField(blank=True, null=True, default=0.0)
distance_to = models.FloatField(blank=True, null=True, default=0.0)
time_from = models.TimeField(blank=False, null=False ,default=timezone.now)
time_to = models.TimeField(blank=False, null=False ,default=timezone.now)
source = models.CharField(max_length=100, blank=True, null=True)
destination = models.CharField(max_length=100, blank=True, null=True)
doeking_km = models.FloatField(blank=True, null=True, default=0.0)
And here is my views for creating logsheet
def create_logsheet(request):
drivers = Driver.objects.all()
vehicles = Vehicle.objects.all()
if request.method == "POST":
vehicle_id = request.POST.get("vehicle")
vehicle = Vehicle.objects.get(id=vehicle_id)
date = request.POST.get("date")
# logsheet data
trip = request.POST.getlist("trip")
time_from = request.POST.getlist("time_from")
time_to = request.POST.getlist("time_to")
source = request.POST.getlist("source")
destination = request.POST.getlist("destination")
distance_from = request.POST.getlist("distance_from")
distance_to = request.POST.getlist("distance_to")
driver_id = request.POST.getlist("driver")
driver = Driver.objects.filter(id__in=driver_id)
print(driver)
#main logic
if vehicle and driver and date:
log = Log(vehicle=vehicle, date=date)
log.save()
data = zip(trip, driver, distance_from, distance_to,time_from, time_to, source, destination)
for trip,driver, distance_from, distance_to, time_from, time_to, source, destination in data:
if trip and driver and distance_from and distance_to and time_from and time_to and source and destination:
logdetail = Logsheet(
log=log,
trip=trip,
driver=driver,
distance_from=distance_from,
distance_to=distance_to,
time_from=time_from,
time_to=time_to,
source=source,
destination=destination,
)
logdetail.save()
return redirect("logsheet_list")
Problem:
When i want same driver fro multiple trip is it not creating is return only one queryset like <QuerySet [<Driver: Mannu R>]>.
I wanted to save same driver must save from each diffrent trip.
filter returns a QuerySet. Use get instead.
driver = Driver.objects.get(id=driver_id)
And perhaps you should have a look at Django forms. This should simplify your code.

I am working on a django project that involves three models as indicated below Client,Loan,Payment

I am getting alot of duplicates in my template when i try to call the calculated loan payments in templates.
My models:
class Client(models.Model):
full_name = models.CharField(max_length=200,blank=True) staff=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.SET_NULL,null=True,blank=True,related_name="client")
date = models.DateTimeField(default=timezone.now)
class Loan(models.Model):
ref = ShortUUIDField(length=6,max_length=6,alphabet="ABCDZXFQFHKRKL0123456789",unique=True)
loan_amount = models.IntegerField(blank=True,null=True)
staff=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.SET_NULL,null=True,blank=True,related_name="loans")
search_client=models.ForeignKey(Client,on_delete=models.SET_NULL,null=True,blank=True)
#cached_property
def loan_repayments(self):
myfilter = Loan.objects.filter(ref=self.ref,payment__payment_reason='loan repayment')
result=myfilter.aggregate(total=Sum(F('payment__amount')))
total = result['total']
if total is None:
return 0
return total
class Payment(models.Model):
ref = ShortUUIDField(length=6,max_length=6,alphabet="ABCDZXFQFHKRKL0123456789",unique=True)
payment_reason = models.CharField(max_length=200, null=True, blank=True,choices=PAYMENT_REASON,default='loan repayment',db_index=True)
amount = models.IntegerField(blank=True, null=True)
lender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
blank=True, null=True, related_name="payments")
loan = models.ForeignKey(Loan, on_delete=models.CASCADE,
blank=True, null=True)
my view:
class Loan(LoginRequiredMixin,ListView):
query_set =Loan.objects.filter(status="active",action="creating loan").select_related('staff','search_client')
context_object_name = 'transactions'
paginate_by = 15
my template:
duplicates am getting:
duplicates in the toolbar

Calculate the sum and multiply with the quantity to get the total in django

I have the code which calculates the sum just fine, now my question is it possible to multiple each price by quantity and then get the total sum after that in a cart on my website. I have tried with all of my logic but i have failed. The idea is to get the price of an item added to cart and multiply it by quantity and then get the total.
Here is my cart mode. models.py:
#cart model
class Cart(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
number_of_items = models.IntegerField(default=0)
user = models.ForeignKey(User, on_delete=models.CASCADE)
added_datetime = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.item.name
#Item model
class Item(models.Model):
CONDITION = (
('new', 'new'),
('used', 'used'),
('not applicable', 'not applicable'),
)
name = models.CharField(max_length=250)
owner = models.CharField(max_length=250, default='Ludocs-emark')
category = models.ForeignKey(ItemCategories, on_delete=models.CASCADE)
sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
Condition = models.CharField(max_length=250, null=True, choices=CONDITION)
price= models.IntegerField(default=0)
number_of_items = models.IntegerField(blank=True)
specification_one = models.CharField(max_length=250, blank=True)
specification_two = models.CharField(max_length=250, blank=True)
specification_three = models.CharField(max_length=250, blank=True)
specification_four = models.CharField(max_length=250, blank=True)
specification_five = models.CharField(max_length=250, blank=True)
specification_six = models.CharField(max_length=250, blank=True)
available_colors = models.CharField(max_length=250, blank=True)
description = RichTextField()
thumbnail = models.ImageField(default='default.png', upload_to='images/')
image_one = models.ImageField(upload_to='images/')
image_two = models.ImageField(upload_to='images/')
image_three = models.ImageField(upload_to='images/')
image_four = models.ImageField(upload_to='images/')
added_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
views.py file that i used to calculate the sum:
#This is the file where that i want to use to get the items added in cart and then multiply each by it's quantity and then get the total of the calculations when multiplied.
cart_sum = Cart.objects.filter(user=request.user).aggregate(Sum('item__price')).get('item__price__sum')
Yes, You can do that.
Try this
cart_sum = Cart.objects.filter(user=request.user).aggregate(Sum('item__price', field='item__price * number_of_items')).get('item__price__sum')
Assuming number_of_items as the quantity for the item from the Cart model.
Also you can return a total value so that if this gives any error for two different fields then you can do this
cart_sum = Cart.objects.filter(user=request.user).aggregate(total_price=Sum('item__price', field='item__price * number_of_items')).get('total_price')

Add extra column to tables in django_tables2

I want to add extra-column which is not in my model. And I apply one of the solutions at this site to my project. But it doesn't work properly.
model.py
class Companies(models.Model):
legal_name = models.CharField(max_length=120, blank=True)
co_name = models.CharField(max_length=120, blank=True)
client = models.ForeignKey(Clients, models.SET_NULL, blank=True, null=True)
tel_no = models.CharField(max_length=120, blank=True)
email = models.EmailField(null=True, blank=True)
address = models.TextField(null=True, blank=True)
contact = models.CharField(max_length=250, blank=True)
con_tel_no = models.CharField(max_length=120, blank=True)
entity = models.CharField(max_length=2, null=True)
yearend = models.DateField(null=True, blank=True)
bn = models.CharField(max_length=9)
memo = models.TextField(null=True, blank=True)
slug = models.SlugField(null=True, blank=True)
def t2_due_date(self):
now_year = datetime.date.today().year
if self.entity == 'CO':
yearend_ = DateWidget.decompress(self, self.yearend)
if yearend_[1] > 6:
yearend_[2] = now_year + 1
yearend_[1] -= 6
else:
yearend_[2] = now_year
yearend_[1] += 6
t2_due = DateWidget.compress(self, yearend_)
return t2_due
tables.py
class ScheduleTable(tables.Table):
due_date_col = tables.Column(accessor='t2_due_date', verbose_name='T2 Due Date')
class Meta:
attrs = {"class": "paleblue", "width":"100%"}
fields = ['client','legal_name', 'co_name', 'entity', 'yearend', 'due_date_col']
model = Companies
When I run this program 'due_date_col' is always blank. It seems that the function('t2_due_date) does not go through. Do you have any clue to clear this problem?
As far as I know accessor points to related objects, rather than model's properties, methods etc.
What you can try is to make use of Table.render_{column} as so:
class ScheduleTable(tables.Table):
def render_due_date_col(self, record):
return record.t2_due_date()
See djanog tables official doc for more info.