How to get the minimum value of an instance of django model - django

I am trying to get the minimum or the lowest value of a model field in django model. The field is room_Price. I am therefore trying to get the minimum of value of this field for each instance of a model. My model are as as follows
class Hotels(models.Model):
name = models.CharField(max_length=255)
address = models.CharField(max_length=255)
city = models.CharField(max_length=255)
country = models.CharField(max_length=255)
mobile_number = models.CharField(max_length=12)
created_at = models.DateTimeField(default=timezone.now)
last_modified = models.DateTimeField(auto_now=True)
description = models.TextField()
slug = models.SlugField(unique=True)
property_photo = models.ImageField(default='default.jpg', upload_to='hotel_photos')
star_rating = models.PositiveIntegerField()
contact_person = models.ForeignKey(UserProfile, on_delete = models.CASCADE, null=True, blank=True,)
class Room(models.Model):
hotel = models.ForeignKey(Hotels,on_delete = models.CASCADE, null=True, blank=True,)
room_photo = models.ImageField(default='default.jpg', upload_to='room_photos')
room_Name = models.CharField(max_length = 200)
room_details = models.CharField(max_length = 500)
room_Capacity = models.PositiveIntegerField(default = 0)
slug = models.SlugField(unique=True)
# guest_numbers = models.IntegerField(default=0)
room_Price= models.PositiveIntegerField(default = 0)
total_Rooms = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, blank=True,)
More details
From the above models, a hotel can have as many rooms as possible. Now i want to fetch the lowest priced room for each hotel. I tried to use Hotels.objects.aggregate(min_price=Min('room__room_Price')) but it is fetching the overall minimum price of all the hotel rooms. Kindly assist

You can try to add ordering to your model and then find lowest price in a loop:
class Room(models.Model):
...
class Meta:
ordering = ['room_Price']
And filter in views:
lowest_prices = {}
for i in Hotels.objects.all():
price = Room.objects.filter(hotel=i.id)[0].room_Price
lowest_prices[i.name] = price
print(lowest_prices)
I put prices in a dict, but you can do anything you want with it.

Related

Django rest Ecommerce category and product offers

I'm trying to acheive catgeory and product offers in my project and am unable to come up with a solution. Like if i give offer to a category all products price in category should get the offer and for products its individual.
class Category(models.Model):
category_name = models.CharField(max_length=15, unique=True)
slug = models.SlugField(max_length=100, unique=True)
class Meta:
verbose_name_plural = "Category"
class Products(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
product_name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(max_length=100, unique=True)
description = models.TextField(max_length=500)
price = models.IntegerField()
images = models.ImageField(upload_to="photos/products")
images_two = models.ImageField(upload_to="photos/products")
images_three = models.ImageField(upload_to="photos/products")
stock = models.IntegerField()
is_available = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = "Products"
def __str__(self):
return self.product_name
class CategoryOffer(models.Model):
category = models.OneToOneField(Category, on_delete=models.CASCADE, related_name='cat_offer')
valid_from = models.DateTimeField()
valid_to = models.DateTimeField()
discount = models.IntegerField(
validators=[MinValueValidator(1), MaxValueValidator(100)]
)
is_active = models.BooleanField(default=False)
def __str__(self):
return self.category.category_name
class ProductOffer(models.Model):
product = models.OneToOneField(Products, on_delete=models.CASCADE, related_name='pro_offer')
valid_from = models.DateTimeField()
valid_to = models.DateTimeField()
discount = models.IntegerField(
validators=[MinValueValidator(1), MaxValueValidator(100)]
)
is_active = models.BooleanField(default=False)
def __str__(self):
return self.product.product_name
So above are my models. I don't know how to implement, thought of many ways but it keeps leading to errors.
You are using separate models for Categoryoffer and Productoffer. Make an Offer model with the following field:
class Offer:
name = models.CharField()
valid_from = models.DateTimeField()
valid_to = models.DateTimeField()
discount = models.IntegerField(
validators=[
MinValueValidator(1),
MaxValueValidator(100)
])
is_active = models.BooleanField(default=False)
Now use the foreign key in your category and product models:
class Product:
offer = models.ForeignKey(Offer)

I want to select as much as member CustomUser(which is Agents Model instances) while creating a project

Filter A foreignkey child model instance in a form field based on the parent value selected in another field in the same field
class Agents(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE)
address = models.TextField()
gender = models.CharField(max_length=50)
numero_telephone = models.CharField(max_length=50)
departement_id = models.ForeignKey(Departements, on_delete=models.CASCADE, default=1)
role_id = models.ForeignKey(Roles, on_delete=models.CASCADE, default=1)
profile_pic = models.FileField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class Projets(models.Model):
id = models.AutoField(primary_key=True)
projet_name = models.CharField(max_length=255)
departement_id = models.ForeignKey(Departements, on_delete=models.CASCADE, default=1) #need to give defauult course
manager_id = models.CharField(max_length=255, null=True,blank=True)
membres_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()

Filter A foreignkey child model instance in a form field based on the parent value selected in another field in the same field

Filter A foreignkey child model instance in a form field based on the parent value selected in another field in the same field
class Agents(models.Model):
id = models.AutoField(primary_key=True)
admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE)
address = models.TextField()
gender = models.CharField(max_length=50)
numero_telephone = models.CharField(max_length=50)
departement_id = models.ForeignKey(Departements, on_delete=models.CASCADE, default=1)
role_id = models.ForeignKey(Roles, on_delete=models.CASCADE, default=1)
profile_pic = models.FileField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()
class Projets(models.Model):
id = models.AutoField(primary_key=True)
projet_name = models.CharField(max_length=255)
departement_id = models.ForeignKey(Departements, on_delete=models.CASCADE, default=1) #need to give defauult course
manager_id = models.CharField(max_length=255, null=True,blank=True)
membres_id = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager()

How to add ArrayField in Django?

my models.py
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_details = models.TextField(default='')
mentor_id = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
doubtClass = models.OneToOneField(DoubtClasses, on_delete=models.PROTECT, null=True, blank=True)
isDraft = models.BooleanField(default=True)
ratings = models.FloatField(default=0)
no_of_students_registered = models.IntegerField(default=0)
# registered_students = models.ManyToManyField(RegisteredNames, null=True, blank=True)
no_of_students_attended = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'LiveClass_details'
class RegisteredNames(models.Model):
name = models.CharField(max_length=100, unique=True)
liveclass_id = models.ForeignKey
I am creating a endpoint where when a user register himself his name will get added to registered_students , so i had made a registered students ManyToMany Field hoping it will get updated when a user is registered but then i understand that it will contain all the names that are present in the RegisteredNames Model meaning names registered across all the liveclasses but i want only the names that are registered for a particular liveclass in the field so i need a array like field which i think is not possible so please help me in improving my logic, how can i achieve it
The documentation and django tutorials are very good: https://docs.djangoproject.com/en/3.2/topics/db/models/ https://docs.djangoproject.com/en/3.2/intro/tutorial02/#creating-models
Your code is very close. You don’t need the many-to-many field, and you need to specify the type of the Foreign key relationship in the RegisteredNames. You can do this:
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_details = models.TextField(default='')
mentor_id = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
doubtClass = models.OneToOneField(DoubtClasses, on_delete=models.PROTECT, null=True, blank=True)
isDraft = models.BooleanField(default=True)
ratings = models.FloatField(default=0)
no_of_students_attended = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'LiveClass_details'
class RegisteredNames(models.Model):
name = models.CharField(max_length=100, unique=True)
liveclass = models.ForeignKey(LiveClass_details, on_delete=Models.CASCADE)
Then, simply:
name = RegisteredNames.objects.create(name="Dhruv", liveclass_id=1)
To get all the registered names from a liveclass_details:
names = LiveClass_details.objects.get(id=1).registerednames_set.all()
num_reg = len(names)

Vendor id where to place in ecommerce app Django

class Product(models.Model):
title = models.CharField(max_length =120)
slug = models.SlugField(blank=True)
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99)
image = models.ImageField(upload_to=upload_image_path,null=True, blank=True)
featured = models.BooleanField(default=False)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True)
class OrderItem(models.Model):
item = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
item_cart = models.CharField(max_length=20, null=True, blank=True)
class Cart(models.Model):
user = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE)
products = models.ManyToManyField(OrderItem, blank=True)
subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
total = models.DecimalField(default=0.00,max_digits=100,decimal_places=2)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
where to place the vendor id in this model and how to implement for many shops with this datamodel
i did ecom website with this data model for a single shop