manytomanyfield distinct value - django

i have a model called mti(Material Information) which have a list of MTD(Material Description) and in each material description description there is a size and color
i have an MTI id i want to get all the distinct list of color values
mymti = mti.objects.get(pk=1)
how can i get the list of colors from MTI
mymti.mtd.color.name ?
class color(models.Model):
id = models.AutoField(primary_key=True)
name= models.CharField(max_length=255)
stamp= models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.name
class mtd(models.Model):
id = models.AutoField(primary_key=True)
barcode = models.CharField(max_length=255)
#mti = models.ManyToManyField(mti)
size = models.ForeignKey(size)
color = models.ForeignKey(color)
weight = models.FloatField()
def __unicode__(self):
return u'%s - %s %s' % (self.barcode,self.color.name,self.size.name)
class Meta:
verbose_name = "MTD"
verbose_name_plural = verbose_name
class mti(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
item = models.ForeignKey(item)
mtd= models.ManyToManyField(mtd)
country = models.ForeignKey(country)
dept = models.ForeignKey(dept)
fabric = models.ForeignKey(fabric)
sesason = models.ForeignKey(season)
sale = models.FloatField()
endUser = models.FloatField()
description = models.TextField(max_length=1000,blank=True,null=True)
year = models.CharField(max_length=255,default=strftime("%Y", gmtime()))
front_page = models.BooleanField(verbose_name="Front Page",default=True)
active = models.BooleanField(default=True)
stamp = models.DateTimeField(auto_now=True)
def __unicode__(self):
return u'%s - %s' % (self.name, self.description)
class Meta:
verbose_name = "MTI"
verbose_name_plural = verbose_name
class mtiimage(models.Model):
id = models.AutoField(primary_key=True)
mtd = models.ManyToManyField(mtd)
image1 = models.ImageField(verbose_name="Product 1 Image",upload_to='product')
image2 = models.ImageField(verbose_name="Product 2 Image",upload_to='product')
image3 = models.ImageField(verbose_name="Product 3 Image",upload_to='product')
stamp = models.DateTimeField(auto_now=True)
def admin_thumbnail(self):
return u'<img src="%s" heigh="150" width="200" />' % (self.image1.url)
admin_thumbnail.short_description = 'Thumbnail'
admin_thumbnail.allow_tags = True
def __unicode__(self):
return u'%s ' % (self.id)
class Meta:
verbose_name = "MTI Image"
verbose_name_plural = verbose_name

Annotation
Use annotation.
mymti = mti.objects.get(pk=1)
unique_colors = mymti.mtd.values_list('color__name', flat=True).annotate()

colors = mymti.mtd.values_list('color__name', flat=True).distinct()
will result in :
colors = [color1, color2, ...]

Related

Django ORM query for filtering product price between two number is not working properly

class Product(models.Model):
product_name = models.CharField(max_length=255,unique=True)
slug = models.SlugField(max_length=255)
brand = models.CharField(max_length=255)
price = models.CharField(max_length=255)
product_image_1 = models.ImageField(upload_to = 'photos/product',blank = False)
product_image_2 = models.ImageField(upload_to = 'photos/product', blank = False)
product_image_3 = models.ImageField(upload_to = 'photos/product', blank = False)
product_image_4 = models.ImageField(upload_to = 'photos/product',blank = False)
product_description = models.TextField()
category_id = models.ForeignKey(Categories,on_delete=models.CASCADE)
subcategory_id = models.ForeignKey(SubCategories, on_delete=models.CASCADE)
stock = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.product_name
def get_url(self):
return reverse('product_detail',args = [self.category_id.slug , self.subcategory_id.slug,
self.slug ])
'''view'''
val=request.POST.get('value')
val = re.findall("\d+", val) # code to get all inigers from string
min_price = int(val[0])
max_price = int(val[1])
print(min_price)
print(max_price)
***product = Product.objects.filter(category_id = categories,is_active =
True,price__gte = min_price, price__lte = max_price)***
when i give value greater than max_value product object returns null object
I want all objects between the two min_value and max_value

Summing up total amount from multiple models in Django

The title of my question has said it all. I have multiple models, and I want to add up the amount to derive the total amount, here's my code
class FurnitureItem(models.Model):
fur_title = models.CharField(max_length=200)
fur_price = models.FloatField()
fur_discount_price = models.FloatField(blank=True, null=True)
fur_pictures = models.ImageField(upload_to='Pictures/', blank=True)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24)
fur_descriptions = models.TextField()
slug = models.SlugField()
date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.fur_title
class FurnitureOrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
fur_ordered = models.BooleanField(default=False)
item = models.ForeignKey(FurnitureItem, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
def __str__(self):
return f"{self.quantity} of {self.item.fur_title}"
....
def get_final_fur_price(self):
if self.item.fur_discount_price:
return self.get_total_discount_fur_price()
return self.get_total_item_fur_price()
class FurnitureOrder(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
fur_items = models.ManyToManyField(FurnitureOrderItem)
date_created = models.DateTimeField(auto_now_add=True)
ordered_created = models.DateTimeField()
fur_ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.username
def get_total_fur_everything(self):
total = 0
for fur_order_item in self.fur_items.all():
total += fur_order_item.get_final_fur_price()
return total
class GraphicItem(models.Model):
graphic_title = models.CharField(max_length=200)
graphic_price = models.FloatField()
graphic_discount_price = models.FloatField(blank=True, null=True)
graphic_pictures = models.ImageField(upload_to='Pictures/', blank=True)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24)
graphic_descriptions = models.TextField()
slug = models.SlugField()
date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.graphic_title
class GraphicOrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
graphic_ordered = models.BooleanField(default=False)
item = models.ForeignKey(GraphicItem, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
def __str__(self):
return f"{self.quantity} of {self.item.graphic_title}"
....
def get_final_graphic_price(self):
if self.item.graphic_discount_price:
return self.get_total_discount_graphic_price()
return self.get_total_item_graphic_price()
class GraphicOrder(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
graphic_items = models.ManyToManyField(GraphicOrderItem)
date_created = models.DateTimeField(auto_now_add=True)
ordered_created = models.DateTimeField()
graphic_ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.username
def get_total_graphic_everything(self):
total = 0
for graphic_order_item in self.graphic_items.all():
total += graphic_order_item.get_final_graphic_price()
return total
what i've tried as regards summing up the amount for furniture and graphics
class TotalAmount(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
graphic_items = models.ManyToManyField(GraphicOrderItem)
fur_items = models.ManyToManyField(FurnitureOrderItem)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
def amount(self):
return self.graphic_items.get_total_graphic_everything() + self.fur_items.get_total_fur_everything()
Then my views goes this way:
class Summary(LoginRequiredMixin, View):
def get(self, *args, **kwargs):
try:
fur_order = FurnitureOrder.objects.get(user=self.request.user, fur_ordered=False)
graphic_order = GraphicOrder.objects.get(user=self.request.user, graphic_ordered=False)
amount = TotalAmount.objects.get(user=self.request.user)
context = {
'fur_order':fur_order,'graphic_order':graphic_order,'amount':amount}
return render(self.request, 'business/home-order-summary.html', context)
Thanks for your time, I no the code is lengthy, but I wanted to expanciate better.

Django: method of model from querying a different one

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

dependent field of others in django admin

I have a model
class Essai_Fluage(models.Model):
name = models.ForeignKey(Material, verbose_name=_('name'))
elongation= models.FloatField(_('allongement'),blank=True, null=False)
t_02 = models.IntegerField(_('t_0.2%'),blank=True, null=False)
t_05 = models.IntegerField(_('t_0.5%'),blank=True, null=False)
t_075 = models.IntegerField(_('t_0.75%'),blank=True, null=False)
tr = models.IntegerField(_('tr'),blank=True, null=False)
T= models.FloatField(_('temperature'),blank=True, null=False)
sigma = models.FloatField(_('contrainte'),blank=True, null=False)
PLM = models.FloatField(_('PLM'),blank=True, null=False)
rep = models.IntegerField(_('indice'),blank=True, null=True)
def __unicode__(self):
return '%s' % (self.name)
class Meta:
verbose_name = _('creep test')
verbose_name_plural = _('creep test')
ordering = ['rep',]
I would like to have the field PLM calculate with the formula
PLM = (T/1000)*(20 + log10(tr))
T and tr are the fields
T= models.FloatField(_('temperature'),blank=True, null=False)
tr = models.IntegerField(_('tr'),blank=True, null=False)
in the admin, is it possible to do this ?
You can override save method of model to calculate the value from the formula.
Try this :
class Essai_Fluage(models.Model):
name = models.ForeignKey(Material, verbose_name=_('name'))
elongation= models.FloatField(_('allongement'),blank=True, null=False)
t_02 = models.IntegerField(_('t_0.2%'),blank=True, null=False)
t_05 = models.IntegerField(_('t_0.5%'),blank=True, null=False)
t_075 = models.IntegerField(_('t_0.75%'),blank=True, null=False)
tr = models.IntegerField(_('tr'),blank=True, null=False)
T= models.FloatField(_('temperature'),blank=True, null=False)
sigma = models.FloatField(_('contrainte'),blank=True, null=False)
PLM = models.FloatField(_('PLM'),blank=True, null=False)
rep = models.IntegerField(_('indice'),blank=True, null=True)
def __unicode__(self):
return '%s' % (self.name)
class Meta:
verbose_name = _('creep test')
verbose_name_plural = _('creep test')
ordering = ['rep',]
def save(self, *args, **kwargs):
if self.PLM is not None:
self.PLM = (self.T/1000)*(20 + log10(self.tr))
super(Essai_Fluage, self).save(*args, **kwargs)

Exclude entire QuerySet from results

I have the following models:
class LibraryEntry(models.Model):
player = models.ForeignKey(Player)
player_lib_song_id = models.IntegerField()
title = models.CharField(max_length=200)
artist = models.CharField(max_length=200)
album = models.CharField(max_length=200)
track = models.IntegerField()
genre = models.CharField(max_length=50)
duration = models.IntegerField()
is_deleted = models.BooleanField(default=False)
class Meta:
unique_together = ("player", "player_lib_song_id")
def __unicode__(self):
return "Library Entry " + str(self.player_lib_song_id) + ": " + self.title
class BannedSong(models.Model):
lib_entry = models.ForeignKey(LibraryEntry)
def __unicode__(self):
return "Banned Library Entry " + str(self.lib_entry.title)
I'd like to do a query like this:
banned_songs = BannedSong.objects.filter(lib_entry__player=activePlayer)
available_songs = LibraryEntry.objects.filter(player=activePlayer).exclude(banned_songs)
Basically if a song is banned, I want to exclude it from my set of available songs. Is there a way to do this in Django?
banned_song_ids = (BannedSong.objects.filter(lib_entry__player=activePlayer)
.values_list('lib_entry', flat=True))
available_songs = (LibraryEntry.objects.filter(player=activePlayer)
.exclude('id__in' = banned_song_ids))
The alternative is:
available_songs = (LibraryEntry.objects.filter(player=activePlayer)
.filter(bannedsong__isnull = True))