Django Subquery many values - python-3.x

class Category(models.Model):
name = models.CharField(max_length=100)
date = models.DateTimeField(auto_now=True)
class Hero(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
I want Categoty model name, data, id
In cookbook , I wrote the code as above.
hero_qs = Hero.objects.filter(
category=OuterRef("pk")
).order_by("-benevolence_factor")
Category.objects.all().annotate(
most_benevolent_hero=Subquery(
hero_qs.values('name')[:1]
)
)
It seems that only one value can be entered in hero_qs.values('name')
Is it possible to get name, data, id with one annotate?

You can try Concatenating the fields if you really want to use a single annotation
from django.db.models import Subquery, OuterRef, CharField, Value as V
from django.db.models.functions import Concat
hero_qs = Hero.objects.filter(
category=OuterRef("pk")
).order_by("-benevolence_factor").annotate(
details=Concat('name', V(','), 'id', output_field=CharField())
)
Category.objects.all().annotate(
most_benevolent_hero=Subquery(
hero_qs.values('details')[:1]
)
)
Then you can use string interpolation to separate that data out which is a relatively inexpensive operation
name, id = category.most_benevolent_hero.split(',')

Related

Django rest framework cast foreign mysql foreign table column

please help me to convert cast foreign table(customers) first name
class LoandetailListSearch(generics.ListAPIView):
serializer_class = LoandetailSerializer
def get_queryset(self):
"""
Optionally restricts the returned loan details to a search list,
by filtering against a `fields` in query parameter in the URL.
"""
queryset = Loandetails.objects.all().exclude(broker_name__isnull=True).\
extra(
{
'staff': "CONVERT(CAST(CONVERT(CONCAT(staff ) using latin1) as binary) using utf8)",
'customer__first_name': 'SELECT CONVERT(CAST(CONVERT(CONCAT(first_name ) using latin1) as binary) using utf8) as first_name FROM customers WHERE customers.id = loan_details.customer_id'
}).\
extra(select={'customer__first_name': 'SELECT CONVERT(CAST(CONVERT(CONCAT(first_name ) using latin1) as binary) using utf8) as first_name FROM customers WHERE customers.id = loan_details.customer_id' })
return queryset
I tried to convert and cast both methods first_name, But no luck. Thanks

Left Join in Django

I have the following models:
class Patient(models.Model):
patient_first_name = models.CharField(max_length=50)
patient_last_name = models.CharField(max_length=50)
patient_name = models.CharField(max_length=100)
patient_email = models.EmailField(max_length=100)
gender = models.CharField(max_length=50)
class PatientMedicalRecord(models.Model):
patient = models.ForeignKey(Patient)
mrn = models.CharField(max_length=50, unique=True)
patient_height = models.IntegerField(blank=True, null=True)
patient_weight = models.IntegerField(blank=True, null=True)
age_risk = models.BooleanField(default=False)
I want to query on patient table for getting all the patient. also i need MRN column value from PatientMedicalRecord table which contain record for particular patient if exists.
How can i do this with djnago ORM?
Following are sql query gives me perfect result.
SELECT a.id,--remaining field, b.mrn FROM patient as a LEFT JOIN patient_medical_record as b ON a.id=b.patient_id;
How can i do this with django annotate ?
You can fetch related objects using the object_set. In your example, here is how you would do it:
patient = Patient.objects.get(pk=1) # You can use any attribute to get the Patient object
patient_medical_records = patient.patientmedicalrecord_set.all()
patient_mrns = []
for record in patient_medical_records:
patient_mrns.append(record.mrn)
You can also defined a related_name property in your model for the relationship to query relationships with. For example:
class PatientMedicalRecord(models.Model):
patient = models.ForeignKey(Patient, on_delete=models.CASCADE, related_name='patient_records')
Then you would query it like this:
patient = Patient.objects.get(pk=1)
patient_medical_records = patient.patient_records.all()

fetching not with custom primary id in django

I have created a table in which the primary id have to customize id product_id like
class Product(models.Model):
product_id = models.BigIntegerField(auto_created = True,primary_key = True, unique=True)
name = models.CharField(max_length=200)
ref = models.CharField(max_length=100)
number= models.CharField(max_length=100)
class Meta:
db_table = "products"
def __str__(self):
return self.name
after creating the record I want to get the id of the latest record but when I retrieve the data with this id getting None
product = Product.objects.create(name=name, ref=ref, number=number)
print(product.product_id)
product.product_id id getting null
Pleae give me a solution to why this is happening.
Django will set the primary key of an AutoField or BigAutoField, given that the database supports returning the assigned primary key.
You thus should rewrite the model to:
class Product(models.Model):
product_id = models.BigAutoField(primary_key=True)
# …
The reason for this is that Django does not know what the primary key (pk) of the object is going to be before the object is saved in the database.
That is because Django does not determine the value of the pk for the incoming object, your database does. In order to get the pk, you first have to save the object then retrive its pk.

Creating relationships with ORM Objects before inserting into a Database

Right now I have double the classes for the same data. The first are the Bill and the Expense class, used locally to exchange data within the program. I then I have Bill_Table and Expense_Table, used to exchange data between the program and database. This makes my program needlessly complicated, when I just want one of each.
Bill has a member variable that is a list of Expenses, like so:
class Bill:
vendor = None # type: str
expenses = None # type: list[Expense]
# plenty more variables here
def __init__(self, vendor=None,):
self.vendor = vendor
self.expenses = list()
class Expense:
account = None # type: str
amount = None # type: int
# etc...
My Bill_Table and Expense_Table are set up pretty much identical. I use some functions to convert a Bill into a Bill_table, or Expense into an Expense_Table, or visa versa.
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Bill_Table(Base):
__tablename__ = 'bills'
id = Column(Integer, primary_key=True)
expenses = relationship("Expense_Table")
# etc...
class Expense_Table(Base):
__tablename__ = 'expenses'
id = Column(Integer, primary_key=True)
bill_id = Column(Integer, ForeignKey('bills.id'))
# etc...
How would I map some Expense_Table objects to a Bill_Table object, without connecting to a database? So I could have the same functionality, but also when I insert a Bill_Table into the database, it will also import it's Expense_Table objects with it too?

cqlengine Model __table_name__ is None

I am trying the new cqlengine models as part of the datastax driver. , here I am not able get the table_name from the class
from cassandra.cqlengine.models import Model
class User(Model):
uid = columns.UUID(primary_key=True,default=uuid.uuid4)
fname = columns.Text(primary_key=True,required=True)
lname = columns.Text(primary_key=True,required=True)
user_id = columns.Text(primary_key=True,required=True)
email_id = columns.Text(primary_key=True,required=True)
password = columns.Text(primary_key=True,required=True)
salt = columns.Text(required=True)
User.table_name gives me None.
Do I need to set this ?
From the documentation
Model.table_name
Optional. Sets the name of the CQL table for this model. If left blank, the table name will be the name of the model, with it’s module name as it’s prefix. Manually defined table names are not inherited.
As answered on the mailing list, considering the __table_name__ can also be dynamically computed based on the name of the model, the way to get the table name is using User.column_family_name(include_keypspace=False).

Resources