Python Django Multi Level Join Query - django

Task Details
I am working on creating a custom API to fetch data from three tables, based on provided key info.
Background
To elaborate, I've three data tables - Client, Account and Client_accounts and their structure looks like this:
Client
ID (Integer) Primary Key
display_name (varchar)
Accounts
ID (Integer) Primary Key
nickname (varchar)
Client_Accounts
Client_ID (Integer) Foreign Key -> ID from client table
Account_ID (Integer) Foreign Key -> ID from accounts table
In intend to pass a client ID to my API and want to fetch all the accounts (and accounts names) owned by that client.
The SQL query that I am trying to replicate looks like this:
select
cl.id as client_id,
cl.display_name,
ac.id as account_id,
ac.nickname as account_name
from
datahub_clients cl
join
datahub_client_accounts cl_ac
on
cl.id=cl_ac.client_id
join
datahub_accounts ac
on
cl_ac.account_id=ac.id
where
cl.id=15
;
Done so far
This is what I used to fetch the the accounts for a client:
##### For endpoint - get_client_name
#api_view(['GET', 'POST'])
#permission_classes((AllowAny,))
def get_client_name(request):
try:
if request.method == 'GET':
list_of_account_ids = Client_Accounts.objects.filter(client_id=request.GET['id']).values_list('account')
needed_accounts = Accounts.objects.filter(id__in=list_of_account_ids).values('id','nickname')
return Response({'requested client id':request.GET['id'],'identified client name': 'detailed info to go here'}, status=status.HTTP_200_OK)
else:
return Response({'status':'error','message': 'Facepalm moment!'}, status=status.HTTP_403_FORBIDDEN)
Problem Statement
1) In the code above, I was able to pull the relevant accounts for a client_id, however, I can only print the details from account table. How do I put client information as well in the output (client_id, nickname - as shown in the SQL query)
2) What is the django replacement for SQL 'old_field_name AS some_new_name'? In the data tables shown above, both the account and client tables have an 'ID' column. I want to put them both together in the same JSON output and to be able to distinguish between then, I would want to rename them.
3) At this point, my queryset has field members from multiple models. How do I serialize them? I understand that I need to write a custom serializer, which would be based on the two models (for the example show above). I am confused about what to specify in the model= section and meta: section.

Related

model relationship and Queries in Django not a clear

what does these lines of code mean in Django View: i couldn't find a details explanation, I came to Django from a Laravel background, so I can understand the models and relationships... thanks
customer = request.user.customer
product = Product.objects.get(id=productId)
order, created = Order.objects.get_or_create(customer=customer, complete=False)
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
customer = request.user.customer
The request object has a user, the user is the authenticated user (if no user is authenticated then the AnonymousUser object is returned instead). In this example the User model (i.e. the user table) has a field called customer and we are accessing that field.
product = Product.objects.get(id=productId)
Here we are simply querying the Product table for a specific product with the given productId. Note, Django will raise an error if two records are returned when you use the .get() method (i.e. if two rows in the Product table have the same productId.
order, created = Order.objects.get_or_create(customer=customer, complete=False)
Next we use the get_or_create() method to look up an order based off of the customer (the value of which we extracted above. If an order cannot be found we will create one instead. The value of createdwill be True if a neworder` was created or False if one already existed.
orderItem, created = OrderItem.objects.get_or_create(order=order, product=product)
Just as above we are getting or creating an OrderItem using the order and product fields.

Dynamically creating tables using SQLite and Django

I am given a task for a web application I’m developing currently. Currently, my code allow me to do the necessary saving to the existing tables, but I am unsure of how to do the following task. The task is to dynamically create tables as long as the 'save' button is pressed in my web application. I am using SQLite for my database.
Example: I have the field of 'name'. So the user types Test for the name field. Upon saving, this name is stored in an existing table and register under a id of 1. At the same time, I want to be able to create a new table with its own fields. This table will be named example_(id). So in this case it will be example_1.
I’m a beginner in Django and SQL so if anyone can guide/help me in any way, thank you!
Got the error of
views.py
#api_view(['GET'])
def selected_device(request,pk=None):
if pk != None:
devices = Device.objects.filter(pk=pk)
devicedetail = DeviceDetail.objects.filter(DD2DKEY=pk)
cursor = connection.cursor()
tablename= "dev_interface_" + str(pk)
cursor.execute(f"SELECT interface FROM {tablename} ")
righttable = cursor.fetchall()
devserializer = DeviceSerializers(devices, many=True)
devdserializer = DeviceDetailSerializers(devicedetail, many=True)
interfaces = []
for i in righttable:
interfaces.append(i[0])
for i in interfaces:
data =[{"interface": i}]
interserializer = InterfaceSerializers(data, many = True)
results = {
"device":devserializer.data,
"device_details" : devdserializer.data,
"interface":interserializer.data,
}
return Response(results)
In interfaces, I have the following ['G0/1', 'TenGigabitEthernet1/1/3', 'TenGigabitEthernet1/1/5', 'TenGigabitEthernet1/1/20', 'TenGigabitEthernet1/1/21', 'TenGigabitEthernet1/1/22', 'TenGigabitEthernet1/1/23', 'TenGigabitEthernet1/1/24', 'TenGigabitEthernet1/1/25', 'TenGigabitEthernet1/1/26']
I have mentioned in the comments that you can use database connection with raw SQL. Here is an example for you:
from django.db import connection
# Create a connection with your database
cursor = connection.cursor()
# Execute your raw SQL
cursor.execute("CREATE TABLE NameTable(name varchar(255));")
# Create database records
cursor.execute("INSERT INTO NameTable VALUES('ExampleName')")
# Fetch records from the database
cursor.execute("SELECT * FROM NameTable")
# Get the data from the database. fetchall() can be used if you would like to get multiple rows
name = cursor.fetchone()
# Manipulate data
# Don't forget the close database connection
cursor.close()
This is just a basic example about database connection in Django. Customize it depending on your needs. Here is the official documentation for raw SQL and database connections. Also keep in mind that what you are trying to do may not be the best practice or recommended.

Retrieve data related to one table from other table without a relation

I have two models user and recordings, But I don't have any relation between them I have stored user id in recordings (there can be multiple recordings of one user). and I want the latest recording of user with user object how can I achieve that
class Recording(models.Model):
userid = models.IntegerField()
Hi welcome to stackoverflow.
Please ask your question with some of your code.
I think you can try this:
users = User.objects.all().extra( select={
'last_reco':
'SELECT recordings.field_name FROM recordings WHERE '
'recordings.userid = '
'User.id ORDER BY id DESC LIMIT 1',
})
note: recordings is your recording db name
Than you can access last recording with last_reco attr of user object

Save foreign key in django model by value of other field

I'm dealing with apples and buckets imported from an API. They shall be written into a Django database using the models.
The Rest API holds an ID of buckets which isn't the internal one but saved as external_id in the local Bucket Model.
The local Apple Model has a field bucket which is a models:ForeignKey(Bucket) field.
When retrieving and storing the data I can't find out how to connect those two. Is there a way to simply have Django query for the external_id on the bucket table and then use the resulting row to connect the Foreign Key?
a = Apple(
'name' = apple.name
'count' = apple.count
'bucket' = ???
)
a.save()
You can simply do the following:
a = Apple(name=..., count=...) # note there are no quotes around the field names here
a.bucket = Bucket.objects.get(external_id=external_id_from_your_rest_api)
a.save()

How to get association foreign key IDs in Doctrine 2 without loading the associated object?

Hi I'm having trouble with what I thought would be an easy task.
I am retrieving a post from the database. The Post entity has a field createdBy which is associated to a User entity.
What I would like to do is load Post and User with two separate queries (no join). That means I need to have access to the created_by foreign key integer on the $post object. Doctrine does not seem to expose that at all. A var_dump of post shows createdBy => null. If I join the user on directly in the post query createdBy => User object. Is there no way to get the created_by foreign key integer from post so I can query for the user?
Thanks
Use this on your query:
$q->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS, true);
$q->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
Hydratation is disabled, so you have your result as an array.