Django: method of model from querying a different one - django

I have a model CartItem that has a ForeignKey to a Product model.
Because from Product model I get the description, image, etc.
However, I want to have a method called sub_total that returns and integer. I use this to calculate total to be paid for this CartItem.
This sub_total method query a different model costo_de_los_productos using some of the properties of CartItem. like: self.product.category.name, self.product.name, self.size, self.quantity.
I need to return an Integer from sub_total method.
However, something is not right with me query, if I comment it and return 0 it works, but total is 0.
def sub_total(self):
product_price = costo_de_los_productos.objects.filter(category=self.product.category.name,
product = self.product.name,
size=self.size,
quantity=self.quantity).values_list("price", flat=True)
What could be wrong?
class CartItem(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
size = models.CharField(max_length=20, choices=TAMANIOS)
quantity = models.CharField(max_length=20, choices=CANTIDADES)
file = models.FileField(upload_to='files', blank=True, null=True)
comment = models.CharField(max_length=100, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
step_two_complete = models.BooleanField(default=False)
# def __str__(self):
# return str(self.id) + " - " + str(self.size) + " por " + str(self.quantity)
def sub_total(self):
product_price = costo_de_los_productos.objects.filter(category = self.product.category.name,
product = self.product.name,
size=self.size,
quantity=self.quantity).values_list("price", flat=True)
# print(type(product_price))
return product_price
costo_de_los_productos model:
class costo_de_los_productos(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.IntegerField(default=30)
size = models.CharField(max_length=20, choices=TAMANIOS)
quantity = models.CharField(max_length=20, choices=CANTIDADES)
product model:
class Product(models.Model):
name = models.CharField(max_length=250, unique=False)
slug = models.SlugField(max_length=250, unique=False)
description = models.TextField(blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
image = models.ImageField(upload_to='product', blank=True, null=True)
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def get_url(self):
return reverse('shop:ProdDetail', args=[self.category.slug, self.slug])
def __str__(self):
return '{}'.format(self.name)
category model:
class Category(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to='category', blank=True, null=True)
video = EmbedVideoField(null=True, blank=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def get_url(self):
return reverse('shop:allCat', args=[self.slug])
def __str__(self):
return '{}'.format(self.name)
Image of "costo_de_los_productos" from Admin Panel:
UPDATE 1
Cannot print anything after the product_price query.
def sub_total(self):
print("Enters Subtotal")
print(self.product.category.name)
print(self.product.name)
print(self.size)
print(self.quantity)
product_price = costo_de_los_productos.objects.filter(category=self.product.category.name,
product=self.product.name,
size=self.size,
quantity=self.quantity).values_list("price", flat=True)[0]
print("Line after product_price query")
print(type(product_price))
return product_price
Hard coding the values doesn't return expected integer:
def sub_total(self):
print("Enters Subtotal")
print(self.product.category.name)
print(self.product.name)
print(self.size)
print(self.quantity)
product_price = costo_de_los_productos.objects.filter(category="Stickers",
product="Stickers transparentes",
size="5cm x 5cm",
quantity=300).values_list("price", flat=True)[0]
print("Line after product_price query")
print(type(product_price))
return product_price
prints results:
Enters Subtotal
Stickers
Stickers transparentes
5cm x 5cm
300

Related

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')

'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'

'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'.
i am getting error on 'DemoAppProductUpdateDestroySerializer' object has no attribute 'get_image'. any help, would be appreciated.
'DemoAppProductUpdateDestroySerializer' object has no attribute
'get_image'
models.py
class Product(models.Model):
title = models.CharField(max_length=30)
slug= models.SlugField(blank=True, null=True)
sku = models.CharField(max_length=30)
description = models.TextField(max_length=200, null=True, blank=True)
instruction = models.TextField(max_length=200, null=True, blank=True)
price = models.DecimalField(decimal_places=2, max_digits= 10,)
discount_price= models.DecimalField(decimal_places=2, max_digits= 10, null=True, blank=True)
brand = models.ForeignKey("Brand", null=True, blank=True, on_delete=models.CASCADE)
waist = models.ForeignKey("Waist", null=True, blank=True, on_delete=models.CASCADE)
occasion = models.ForeignKey("Occasion", null=True, blank=True, on_delete=models.CASCADE)
style = models.ForeignKey("Style", null=True, blank=True, on_delete=models.CASCADE)
neck = models.ForeignKey("Neck", null=True, blank=True, on_delete=models.CASCADE)
fit = models.ForeignKey("Fit", null=True, blank=True, on_delete=models.CASCADE)
pattern_type = models.ForeignKey("Pattern_Type", null=True, blank=True, on_delete=models.CASCADE)
color = models.ForeignKey("Color", null=True, blank=True, on_delete=models.CASCADE)
size = models.ManyToManyField("Size", null=True, blank=True)
sleeve = models.ForeignKey("Sleeve_Length", null=True, blank=True, on_delete=models.CASCADE)
material = models.ForeignKey("Material", null=True, blank=True, on_delete=models.CASCADE)
category = models.ManyToManyField('Category', )
default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True, on_delete=models.CASCADE)
created_on = models.DateTimeField(default=timezone.now)
updated_on = models.DateTimeField(null=True, blank=True)
status = models.BooleanField(default=True)
class Meta:
ordering = ["-id"]
def __str__(self): #def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("product_detail", kwargs={"pk": self.pk})
def get_image_url(self):
img = self.productimage_set.first()
if img:
return img.image.url
return img #None
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(pre_save_post_receiver, sender=Product)
def image_upload_to(instance, filename):
title = instance.product.title
slug = slugify(title)
basename, file_extension = filename.split(".")
new_filename = "%s-%s.%s" %(slug, instance.id, file_extension)
return "products/%s/%s" %(slug, new_filename)
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
image = models.ImageField(upload_to=image_upload_to)
created_on = models.DateTimeField(default=timezone.now)
status = models.BooleanField(default=True)
def __unicode__(self):
return self.product.title
views.py
class ProductUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
model = Product
queryset = Product.objects.all()
serializer_class = DemoAppProductUpdateDestroySerializer
permission_classes = [IsAdminUser]
authentication_classes = [BasicAuthentication]
serializers.py
class DemoAppProductUpdateDestroySerializer(serializers.ModelSerializer):
image = serializers.SerializerMethodField()
class Meta:
model = Product
fields=[
"id",
"title",
"slug",
"sku",
"price",
"discount_price",
"image",
]
def get_image(self, obj):
return obj.productimage_set.first().image.url

How do I make sure entered integer is greater than current value before updating model field?

I am using a form that saves to one model to update the most current mileage which is stored in another model. I want to make sure the mileage entered is > or = the current mileage. I havent been able to figure out the right validation or where to write the validation.
I have tried an if statement in the form_valid() of the CreateView and a save() method in the model.
Models.py
class Vehicle(models.Model):
name = models.CharField(blank=True, max_length=100)
make = models.CharField(blank=True, max_length=100)
model = models.CharField(blank=True, max_length=100)
year = models.IntegerField(blank=True, null=True)
vin = models.CharField(blank=True, max_length=17)
gvw = models.IntegerField(blank=True, null=True)
license_plate = models.CharField(blank=True, max_length=100)
purchase_date = models.DateField()
current_mileage = models.IntegerField(blank=True, null=True)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('vehicles:vehicle_detail', kwargs={'pk':self.pk})
#property
def get_current_mileage(self):
return self.current_mileage
class FuelEntry(models.Model):
vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now_add=True)
fuel_choices = (
('EMPTY', 'Empty'),
('1/8', '1/8'),
('1/4', '1/4'),
('1/2', '1/2'),
('3/4', '3/4'),
('FULL', 'Full'),
)
current = models.CharField(max_length=5, choices=fuel_choices)
after = models.CharField(max_length=5, choices=fuel_choices, blank=True)
gallons = models.DecimalField(decimal_places=2, max_digits=5, blank=True, default='0')
cost = models.DecimalField(decimal_places=2, max_digits=5, blank=True, default='0')
mileage = models.IntegerField(blank=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
ordering = ['-date', 'vehicle']
def __str__(self):
return self.vehicle.name
def get_absolute_url(self):
return reverse('fuellog:entry_detail', kwargs={'pk':self.pk})
Views.py
class CreateEntry(CreateView):
model = FuelEntry
fields = ('vehicle', 'current', 'after', 'gallons', 'cost', 'mileage')
def form_valid(self,form):
self.object = form.save(commit=False)
self.object.user = self.request.user
vehicle_id = self.object.vehicle.pk
mileage = self.object.mileage
self.object.save()
current_mileage = Vehicle.objects.filter(id=vehicle_id).get('current_mileage')
if current_mileage > mileage:
raise ValidationError('Incorrect mileage reading')
Vehicle.objects.filter(id=vehicle_id).update(current_mileage=mileage)
return super().form_valid(form)
ValueError at /fuel/new
too many values to unpack (expected 2)

Auto Complete field in django

here are my models
class TimeSlots(models.Model):
start = models.TimeField(null=True, blank=True)
end = models.TimeField(null=True, blank=True)
class Meta:
ordering = ['start']
def __str__(self):
return '%s - %s' % (self.start, self.end)
class Event(models.Model):
event_date = models.DateField(null=False, blank=True)
start = models.OneToOneField(TimeSlots)
end = models.TimeField(null=True, blank=True)
available = models.BooleanField(default=True)
patient_name = models.CharField(max_length=60, null=True, blank=True)
phone_number = PhoneNumberField(blank=True, null=True)
stripePaymentId = models.CharField(max_length=150, null=True, blank=True)
stripePaid = models.BooleanField(null=False, blank=True, default=True)
key = models.UUIDField(primary_key=False, default=uuid.uuid4,
editable=False)
sites = models.ManyToManyField(Site, null=True, blank=True)
class Meta:
verbose_name = u'Scheduling'
verbose_name_plural = u'Scheduling'
def __unicode__(self):
return self.start
def get_absolute_url(self):
url = reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.model_name), args=[self.pk])
return u'%s' % (url, str(self.start))
What I want is that end value of Event Model should be auto filled by the selected Timeslot
like when I choose a start value from timeslot for the event model the end value should automatically be filled
Ok I solved it by adding a clean function in my model
def clean(self):
self.end = self.start.end
It was that simple

How To a autoselect Patient Name field when bed assign to patients in Django

How To assign bed to Patient Django?
when I try to assign bed to Patient at that time in bedconfig automatically select Patient Name
then wardconfig file open but Patient name is blant, it must be autoselected Patient name
view this image When click on assign bed
but Patient name is blant, it must be autoselected Patient name
models.py Patient model
class Patient(Auditable):
aadhar_no = models.CharField(max_length=12, blank=True,unique=True)
fullname = models.CharField(max_length=50)
firstname = models.CharField(max_length=30)
middlename = models.CharField(max_length=30)
lastname = models.CharField(max_length=30)
CATEGORY_GENDER= (('Male', 'Male'), ('Female', 'Female'))
gender = models.CharField(max_length=6, choices=CATEGORY_GENDER)
CATEGORY_BG= (('Not known','Not known'),('A+', 'A+'), ('A-', 'A-'),('B+', 'B+'),('B-', 'B-'),('AB+', 'AB+'),('AB-','AB-'),('O+','O+'), ('O-','O-'))
blood_group = models.CharField(max_length=10, choices=CATEGORY_BG)
dob = models.DateField() #Date of birth
photo = models.ImageField(upload_to="Patient/", null=True, blank=True)
education = models.CharField(max_length=15, null=True, blank=True)
CATEGORY_OCC= (('Service', 'Service'), ('Retired', 'Retired'),('Housewife', 'Housewife'), ('Business','Business'),('other','other'))
occupation = models.CharField(max_length=15, choices=CATEGORY_OCC,null=True, blank=True) #service, retired, Housewife, Business, others
current_address = models.TextField()
mobile_number = models.CharField(max_length=12)
mobile_number2 = models.CharField(max_length=12, null=True, blank=True)
phone_number = models.CharField(max_length=12, null=True, blank=True)
email = models.CharField(max_length=30, null=True, blank=True)
country = models.ForeignKey(Country , null=True, blank=True, )
state = models.ForeignKey(State , null=True, blank=True)
district = models.ForeignKey(District , null=True, blank=True)
city = models.ForeignKey(City ,null=True, blank=True)
recreational_drugs= models.BooleanField(default=False) #alocohol, smoking,coffine etc.
current_insurance = models.BooleanField(default=False)
#family = models.ForeignKey(Family) # Family
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self): # __unicode__ on Python 2
# return self.fullname
return str(self.fullname)
class Meta:
verbose_name_plural = "Patient"
models.py WardConfog
class WardConfig(Auditable):
bed = models.ForeignKey(Bed)
ward = models.ForeignKey(Ward)
patient=models.ForeignKey(Patient)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
#def __str__(self): # __unicode__ on Python 2
#return self.name
class Meta:
verbose_name_plural = "Wardconfig"
Views.py PatientCreate(CreateView)
class PatientCreate(CreateView):
model = Patient
form_class = PatientForm
def get_success_url(self):
return reverse_lazy( 'patient')
def form_valid(self,PatientForm):
PatientForm.save()
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, PatientForm):
return self.render_to_response(self.get_context_data(form=PatientForm))
Views.py
class WardConfig(Auditable):
bed = models.ForeignKey(Bed)
ward = models.ForeignKey(Ward)
patient=models.ForeignKey(Patient)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
#def __str__(self): # __unicode__ on Python 2
#return self.name
class Meta:
verbose_name_plural = "Wardconfig"
please Guys Help me how auto select Patient Name IN Wardconfig when assign bed
Sorry for English
You can give the view you are using to add a WardConfig record a get_initial method. This assumes you are passing a patient_id kwarg in the URL:
def get_initial(self):
patient = get_object_or_404(Patient, pk=self.kwargs.get('patient_id'))
return {
'patient': patient,
}