I need a query to retrieve the name and id of the 4 model classes (P, B, M, C, Pt) with a concat.
The class Pt has the foreign key to the parents class by the id
The expected result should be like this: Pt.name, Product.num , concat(B.name, M.name, V.name)
I try several approaches and the more similar it's this one
Models:
class B(models.Model):
b_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
class M(models.Model):
m_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
class V(models.Model):
v_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
class Pt(models.Model):
pt_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
class Product(models.Model):
p_id = models.AutoField(primary_key=True)
p_ref_fk = models.DecimalField(max_digits=5, decimal_places=2, null=True)
pt_fk = models.ForeignKey(Pt, on_delete=models.CASCADE)
b_fk = models.ForeignKey(B, on_delete=models.CASCADE)
m_fk = models.ForeignKey(M, on_delete=models.CASCADE)
v_fk = models.ForeignKey(V, on_delete=models.CASCADE)
Query:
# Get all the P related
p = Product.objects.all().filter(pt_fk__pt_id=1116).filter(b_fk__b_id=3).filter(m_fk__m_id=53).filter(v_fk__v_id=352)
# check the query
print(p.query)
# get the results
print(p)
As per i get your question, you need to Concat foreignkey with - Pt.name, Product.num , concat(B.name, M.name, V.name)
queryset = Employee.objects.annotate(fullname=Concat('first_name', 'last_name'))
this is my own example please change as per your requirements
try this too
Related
Struggling with Django query, need some help.
So I would like to get data for 5 different variables, accounts_data = (only username), user_account_data = (name), country_data = (iso_code), category_data = (choice), permisisons_data = (permissions).
All data of the models is connected with UserAccount table, so need to get data from other tables only for existing user_accounts
Example of models:
class Account(models.Model):
username = models.CharField(max_length=30)
password = models.CharField(max_length=50)
status = models.CharField(max_length=60)
class UserAccount(models.Model):
name= models.CharField(max_length=100)
surname = models.CharField(max_length=100)
category= models.ManyToManyField(Category)
account = models.ForeignKey(Account)
country = models.ForeignKey(Country)
permissions = models.ForeignKey(Permissions)
class Country(models.Model):
iso_code = models.CharField(max_length=6)
zip_code = models.CharField(max_length=10)
class Category(models.Model):
choice = models.CharField(max_length=12)
connected_category = models.CharField(max_length=12)
class Permissions(models.Model):
permission = models.CharField(max_length=50)
restriction = models.CharField(max_length=30)
Need to join these 3 tables , can someone give me the ORM queryset . need to show the records on one template based on these three tables.
Models.py
class Item_Table(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=127)
description = models.TextField(null=True,blank=True)
qty_in_ferma_warehouse = models.IntegerField(null=True,blank=True,default=0)
status = models.BooleanField()
ListID = models.CharField(max_length=80, null=True,blank=True)
class Order_Table(models.Model):
id = models.AutoField(primary_key=True)
order_number = models.CharField(max_length=63)
notes = models.TextField()
created_at = models.DateField()
status = EnumField(Choice,max_length=2, null=True,blank=True)
Total_Amount = models.DecimalField(max_digits=18,decimal_places=2)
must_fill_in_items = models.IntegerField()
total_replenish_small_order = models.IntegerField()
order_type = EnumField(Choice3,max_length=2, null=True,blank=True)
delivery_method = EnumField(Choice6, max_length=2, null=True, blank=True)
class Orderitems_Table(models.Model):
id = models.AutoField(primary_key=True)
order_id = models.ForeignKey(Order_Table,on_delete='')
item_id = models.ForeignKey(Item_Table,on_delete='')
qty = models.IntegerField()
next_order_qty = models.IntegerField(null=True,blank=True,default=0)
Rate = models.DecimalField(max_digits=18,decimal_places=2)
Amount = models.DecimalField(max_digits=18,decimal_places=2)
status = EnumField(Choice2,max_length=2,null=True,blank=True)
accumulated_residual_item = models.IntegerField()
accumulated_damaged_item = models.IntegerField()
You can have a many to many field in Order_Table.
items = models.ManyToManyField(Person, through='Orderitems_Table')
then you can query on Order_Table model and have a queryset
you can go through the documentation to have more insights about ManyToMany Field and how to play with this
For forms and view you can follow this link
I am trying to do what one might consider an advanced sql query and would like to know if its possible in Django without resorting to raw sql (I will if its necessary).
I want to join 1 or another table based on a value located in a table lookup table and would like to do this entirely in python/django.
The following are rough examples of the models I am using:
class SpecificProduct(models.Model):
specific_product_id = models.AutoField(primary_key=True)
a_field = models.TextField()
something_specific_to_this_model = models.CharField()
class GeneralProduct(models.Model):
other_product_id = models.AutoField(primary_key=True)
text = models.TextField()
TABLE_CATEGORIES = {
1 : SpecificProduct,
2 : GeneralProduct,
}
class ProductCategory(models.Model):
category_id = models.AutoField(primary_key=True)
table_category = models.IntegerField() # Technically represents a table.
category_text = models.CharField(max_length=20)
class Inventory(models.Model):
inventory_id = models.AutoField(primary_key=True)
product_category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE)
product_pk = models.IntegerField() # Technically foreign key to a product table.
quantity = models.IntegerField()
What I want is a method like:
def get_product(category_id, product_pk):
# SQL query magic
return one_object_of_a_specific_product_type
This method should be able to do things like...
Give me the product (model) where the product_category = 1 and the
product_pk = 1. (returns a SpecificProduct model)
Give me the product where product_category = 2 and the product_pk = 50
(returns a GeneralProduct model)
How do you do this query in Django and is this even possible?
Edit:
Based on Kireeti K's response I have created models that look like the following:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
class SpecificProduct(models.Model):
specific_product_id = models.AutoField(primary_key=True)
specific_text = models.TextField()
class GeneralProduct(models.Model):
general_product_id = models.AutoField(primary_key=True)
text = models.TextField()
class ProductCategoryLookup(models.Model):
category_id = models.ForeignKey(ContentType, on_delete=models.CASCADE, primary_key=True)
category_text = models.CharField(max_length=20)
class Inventory(models.Model):
inventory_id = models.AutoField(primary_key=True)
product_category = models.ForeignKey(ContentType, on_delete=models.CASCADE)
product_id = models.PositiveIntegerField()
product = GenericForeignKey('product_category', 'product_id')
quantity = models.IntegerField()
def get_product(category_id, product_pk):
content_type = ContentType.objects.get(id=category_id)
inventory = Inventory.objects.get(product_category=content_type, product_id=product_pk).first()
return inventory.product
You can use a generic-foreign-key to get foreign-key relation with any model sort of dynamically, read about it here. https://docs.djangoproject.com/en/2.1/ref/contrib/contenttypes/#generic-relations
If you rewrite your models using generic-foreign-key then it looks something like this.
class ProductCategory(models.Model):
category_id = models.AutoField(primary_key=True)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
table_category = models. GenericForeignKey() # Technically represents a table.
category_text = models.CharField(max_length=20)
class Inventory(models.Model):
inventory_id = models.AutoField(primary_key=True)
product_category = models.ForeignKey(ProductCategory,
on_delete=models.CASCADE)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
product = models. GenericForeignKey() # Technically foreign key to a product table.
quantity = models.IntegerField()
Now to achieve what you want, you can implement your function like this.
def get_product(model=None, category_id, product_pk):
model = "specificproduct" if model else "generalproduct"
content_type = ContentType.objects.get(model=model)
inventory = Inventory.objects.get(product_category_id=category_id, object_id=product_pk, content_type=content_type)
return inventory.product
In the following example from django documentation, how to get
Publisher.objects.all()
annotated with field average_rating computed using average of book ratings and max_rating computed using maximum rating of books?
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Publisher(models.Model):
name = models.CharField(max_length=300)
num_awards = models.IntegerField()
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
pubdate = models.DateField()
class Store(models.Model):
name = models.CharField(max_length=300)
books = models.ManyToManyField(Book)
registered_users = models.PositiveIntegerField()
Precisely I should be able to print something like this after the queryset:
for p in Publisher.objects.all().annotate(...):
print p, p.average_rating, p.max_rating
You can access books of publisher using book__rating like this:
Publisher.objects.annotate(average_rating=Avg('book__rating'), max_rating=Max('book__rating'))
I have a task:
To make a database model with essentially 'student' and 'group'.
'Student' contains: 'Name', 'student ID card', 'group' (must be ForeigKey to Group!)
'Group' contains: 'group name' and 'captain' (must be foreign key to Student!)
Now I have a collision - right straight it's impossible. So I did it in this way:
class Group(models.Model):
group_name = models.CharField(max_length=50)
class Student(models.Model):
name = models.CharField(max_length=50)
birth_date = models.DateField()
std_ID_card = models.IntegerField()
group = models.ForeignKey(Group)
class Captain(models.Model):
student = models.OneToOneField(Student)
group = models.OneToOneField(Group)
Do I have more elegant and correct way to do this?
Try to add a related_name:
class Student(models.Model):
name = models.CharField(max_length=50)
birth_date = models.DateField()
std_ID_card = models.IntegerField()
group = models.ForeignKey('Group')
class Group(models.Model):
group_name = models.CharField(max_length=50)
captain = models.ForeignKey('Student', related_name='%(class)s_captain')
Why is the original structure impossible?
class Group(models.Model):
group_name = models.CharField(max_length=50)
captain = models.ForeignKey('Student')
class Student(models.Model):
name = models.CharField(max_length=50)
birth_date = models.DateField()
std_ID_card = models.IntegerField()
group = models.ForeignKey(Group)