here is models.py
class Product(models.Model):
brand = models.ForeignKey(Brand , related_name='products')
category = models.ForeignKey('Category', verbose_name='categories', related_name='products' , default='')
parent = models.ForeignKey('self' , related_name = 'children' , null=True , blank=True)
title = models.CharField(max_length=500)
class StoreProduct(models.Model):
product = models.ForeignKey('products.Product')
category = models.ForeignKey('products.Category')
store = models.ForeignKey('Store')
class Store(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL , null=True , blank=True)
StoreName = models.CharField(max_length=50 , default = '')
items = models.ManyToManyField('products.Product', through=StoreProduct)
brand = models.ForeignKey('products.Brand' , null=True , blank=True)
City = models.CharField(max_length=50 , default = '')
Area = models.CharField(max_length=50 , default = '')
Address = models.TextField(max_length=500)
MallName = models.CharField(max_length=50 , null=True , blank=True)
slug = models.SlugField(blank=True ,unique=True)
here is views.py
queryset = StoreProduct.objects.all().distinct()
Multiple store can contain the same product and but they should appear once on the product grid page.Distinct query is not working.What can i do to show distinct values in the above case?Thanks in Advance
If you are using PostgreSQL, specify the level of distinction:
queryset = StoreProduct.objects.distinct('product')
you can also use it in conjunction with values(), order_by(), etc:
queryset = StoreProduct.objects.values('product').distinct()
I will suggest the following as solution but not the solution; either you choose PosgreSQL as database, specially that the newest Django version is coming with more built-in support for complex data structure, or you try make you own filter as follow (but in case you have large dataset this will be really bad):
store_product_id_list = StoreProduct.objects.values('product').distinct()
store_product_list = []
for obj in store_product_id_list:
store_product_obj = StoreProduct.objects.filter(product_id=obj.get('product')).first()
store_product_list.append(store_product_obj)
Check distinct for more examples
Related
I've 2 tables in a database on phpmyadmin that are connected by a foreign key. The table "bulle" contains the foreign key of the table "site". In enghlish : one "site" can contain some "bulles" (or not) and a "bulle" is always linked to a "site".
class Bulles(models.Model):
id_bulle = models.AutoField(primary_key=True)
num_bulle = models.CharField(max_length=20)
type_bulle = models.CharField(max_length=20)
colories = models.CharField(max_length=20)
latitude = models.FloatField()
longitude = models.FloatField()
date_vidange = models.DateField(
db_column="date_vidange"
)
id_depot = models.ForeignKey(
"Depot", on_delete=models.CASCADE, db_column="id_depot"
)
id_site = models.ForeignKey(
"Site",related_name='bul', on_delete=models.CASCADE, db_column="Id_site"
)
class Meta:
db_table = "bulles"
class Site(models.Model):
id_site = models.AutoField(
db_column="Id_site", primary_key=True
)
nom = models.CharField(
db_column="Nom", max_length=100
)
vitesse_b = models.FloatField(db_column="Vitesse_b") # Field name made lowercase.
vitesse_c = models.FloatField(db_column="Vitesse_c") # Field name made lowercase.
ecart_type_b = models.FloatField(
db_column="Ecart_type_b"
)
ecart_type_c = models.FloatField(
db_column="Ecart_type_c"
)
type_site = models.CharField(
db_column="Type_site", max_length=20
)
longitude = models.FloatField(db_column="Longitude")
latitude = models.FloatField(db_column="Latitude")
Nombre_bulles = models.IntegerField(db_column="Nombre_bulles")
date_vidange = models.DateField(
db_column="Date_vidange")
class Meta:
db_table = "site"
I've created a request to delete a row in "bulle" selected by the id_bulle (primary key). I'd like to get the "id_site" from this selected bulle that I delete in this request. Then, I need to count every "bulles" of the table that have this id_site. After that I would like to change the value of the column "Nombre_bulles" by the number found just before.
def DeleteBulle (request, id_bulle):
try:
id_bulle
param = Bulles.objects.get(pk=id_bulle)
param.delete()
print("Bulle supprimée")
except:
print("Cette bulle n'existe pas")
return redirect('api_bulles_frontend')
return redirect('api_bulles_frontend')
I don't know how to access the value of the Id_site of the "bulle" I'm deleting selected by its id.
I'm sorry for my english, I hope someone here can help me.
Thanks !
I really don't know how I could do that, I can't find it on Internet.
param.id_site.somethingFromTheClass
I want to display only related sub-categories when selecting a parent category in Django admin. How should I structure the model to achieve this? Or is there any packages available?
Code (models.py)
class Category(models.Model):
name = models.CharField(max_length=200 , null=True)
no_of_products = models.IntegerField(blank=True , null =True)
image = models.ImageField(null=True , blank = True)
class SubCategory(models.Model):
main_category = models.ForeignKey('Category' , on_delete= models.SET_NULL , null = True)
name = models.CharField(max_length=200 , null=True)
no_of_products = models.IntegerField(blank=True , null =True)
image = models.ImageField(null=True , blank = True)
I want to create a custom object list in the view and pass it to the template. In the template I want to loop over the list and display the information.
My models are
class CustomUser(AbstractUser):
def __str__(self):
return self.email
class Post(models.Model):
author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
post_url = models.URLField(max_length = 200, blank = True)
slug = models.SlugField(unique=True, blank=True)
class subscription(models.Model):
creator = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='creator',)
booster = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='booster')
sub_value = models.FloatField(blank = True)
sub_id = models.TextField(blank = True)
status = models.BooleanField(default=False)
dateSubscribed = models.DateTimeField(default=timezone.now)
dateSubscriptionEnded = models.DateTimeField(default=timezone.now)
paymentCount = models.FloatField(default= 0)
I want to filter objects from subscription model like below
subs = subscription.objects.filter(booster = request.user)
Then find creators in the above subs object list and for each creator get the name, numbers Posts, and number of Subscribers. Add this to custom list and pass it to the template to loop over and display the information in the template. Can someone help me how to create this custom list. Thanks!
Ok so here are the basics minus the subscribers because I don't see the relation clearly. This is how to parse the name and the number of posts. \
my_list = []
for sub in subs:
name = sub.creator.name
auth_id = sub.creator.id
posts = Post.objects.filter(author=auth_id)
num_of_posts = len(posts)
my_list.append({
'name':name,
'post_count': num_of_posts,
})
then you would pass mylist thru the template context.
It is a common mistake to name the related_name=… parameter [Django-doc] to the same value as the name of the field. The related_name parameter however is the name of the reverse relation Django will automatically add. So here it means a relation to access for example the related subscription objects of a given CustomUser.
Therefore it makes more sense to rename these, for example like:
class Subscription(models.Model):
creator = models.ForeignKey(
CustomUser,
default=None,
null=True,
on_delete=models.CASCADE,
related_name='created_subscriptions'
)
booster = models.ForeignKey(
CustomUser,
default=None,
null=True,
on_delete=models.CASCADE,
related_name='boosted_subscriptions'
)
sub_value = models.FloatField(blank=True)
sub_id = models.TextField(blank =True)
status = models.BooleanField(default=False)
dateSubscribed = models.DateTimeField(default=timezone.now)
dateSubscriptionEnded = models.DateTimeField(default=timezone.now)
paymentCount = models.FloatField(default=0)
Next we can make a query where:
from django.db.models import Count
CustomUser.objects.filter(
created_subscriptions__booster=request.user
).annotate(
number_of_posts=Count('post', distinct=True)
)
This is a QuerySet of CustomUsers where each CustomUser that arises from this QuerySet has an extra attribute .number_of_posts that contains the number of posts. You thus can iterate over the queryset directly in the template.
Model , with abstract base class:
class MapObject(models.Model):
start_date = models.DateTimeField(default= datetime.strptime('1940-09-01T00:00:00', '%Y-%m-%dT%H:%M:%S'))
end_date = models.DateTimeField(default= datetime.strptime('1941-07-01T00:00:00', '%Y-%m-%dT%H:%M:%S'))
description = models.TextField(blank=True)
location = models.PointField()
objects = models.GeoManager()
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add = True)
last_modified = models.DateTimeField(auto_now = True)
source = models.ForeignKey(Source)
address= models.TextField(blank=True, null=True)
address_road = models.TextField(blank=True, null=True)
class Meta:
abstract = True
class Bomb(MapObject, BombExtraManager):
#Bomb Attributes
type = models.CharField(choices= Type_CHOICES, max_length=10)
night_bombing = models.BooleanField(blank=True)
map_sheet = models.ForeignKey(MapSheet, blank=True, null=True)
def __unicode__(self):
return self.type
Now, I want to get the equivalent result using Django ORM as this query:
Select date_part('day',"start_date") as "day", date_part('hour',"start_date") as "hour", Count('id')
from "Mapper_bomb"
where "source_id" = 1
group by date_part('hour',"start_date"), date_part('day',"start_date")
Order by date_part('day',"start_date") ASC, date_part('hour',"start_date") ASC
Which would give me a table with the count of bombs per day and hour.
Using Django ORM, I have come to the following at the moment (first_day is just a custom manager I defined that returns a subset of the data, same as source_id = 1):
Bomb.first_day.extra(select={'date': "date_part(\'day\', \"start_date\")", 'hour': "date_part(\'hour\', \"start_date\")"}).values('date', 'hour').order_by().annotate(Count('date'), Count('hour'))
but Django complains FieldError: Cannot resolve keyword 'date' into field. Is there a way using Django ORM to get the desired result or do I need to fallback on raw sql?
Does this work?
Bomb.first_day.extra({
'date': "date_part(\'day\', \"start_date\")",
'hour': "date_part(\'hour\', \"start_date\")"
}).values('date', 'hour').order_by('date', 'hour').annotate(Count('id'))
Guys,
Is there an easy way to return different fields names from different models by chaining joins?
My model:
Class Item(models.Model):
item_code = models.CharField(max_length=10)
name = models.CharField(max_length=255)
...
Class Stock(models.Model):
item_code = models.ForeignKey( Item )
userid = models.ForeignKey( User )
qty = models.IntegerField()
...
I want to select " Item.Item_code, Item.name, Stock.qty where Stock.userid=2 and Item.item_code = Stock.Item_Code"
How do i do this in Django?
Gath
I want to select " Item.Item_code, Item.name, Stock.qty where Stock.userid=2 and Item.item_code = Stock.Item_Code"
You can pick these specific fields only using one SQL, provided you start from the Stock model. For instance
q = Stock.objects.select_related('userid', 'item_code').filter(
userid__id = 2).values('item_code__item_code', 'item_code__name', 'qty')
This will help if you want to limit the data and then number of queries. If you are not concerned with this then do:
q = Stock.objects.filter(userid__id = 2)
for stock in q:
print stock.item_code.item_code
print stock.item_code.name
print stock.qty
This will return a queryset with only those fields you have chose using values. You can then iterate through it.
PS: Re: your models.
Class Stock(models.Model):
item_code = models.ForeignKey( Item )
userid = models.ForeignKey( User )
qty = models.IntegerField()
...
It is a good idea to use the model name in lower case for FK relationships. For e.g. you ought to write:
Class Stock(models.Model):
item = models.ForeignKey( Item ) # Changed
user = models.ForeignKey( User ) # Changed
qty = models.IntegerField()
...
You can also use this:
Stock.objects.filter(user=2).values('item__item_code', 'item__name')
First of all change fileds names
Read this very carefuly http://docs.djangoproject.com/en/dev/ref/models/querysets/
Class Item(models.Model):
item_code = models.CharField(max_length=10)
name = models.CharField(max_length=255)
...
Class Stock(models.Model):
item = models.ForeignKey( Item )
user = models.ForeignKey( User )
qty = models.IntegerField()
...
#view
stocks = Stock.objects.filter(user=2)
for stock in stocks:
print stock.item.item_code, stock.item.name
#one query version