Doctrine ORM not returning the expected result - doctrine-orm

I am using a Doctrine ORM with Zend Framework 2
I am trying to run a simple query through it. It's not returning the expected output.
$resultObject = $this->getEntityManager()->createQuery('SELECT max(u.displayId) FROM Test\Entity\TestMe u WHERE u.product = 12);
$resultDisplayId =$resultObject->getSingleScalarResult();
The above query should give me 1 but it returns 8. Is there something to do with Cache? Please suggest.Thanks!!

Related

Django queryset with Q gives wrong length

I'm struggling with or query. It give me weird output.
In models file i have as shown below:
class Server:
addres_ip=models.GenericIPAddressField()
class Interface:
addres_ip=models.CharField(max_length=15,default='127.0.0.1',blank=True)
server=models.ForeignKey(Server,default=None,blank=True,null=True,on_delete=models.CASCADE)
In db i have added a Server object with addres_ip='10.0.10.11' and with his Interface with addres_ip='10.1.1.2'.
When i query:
Server.objects.filter(addres_ip='10.0.10.11') I get 1 result and it's correct
Interface.objects.filter(addres_ip='10.0.10.11') I get 0 results and it's correct as well
but when I query:
Server.objects.filter(Q(adress_ip='10.0.10.11') | Q(Interface__adress_ip='10.0.10.11')) i get 7 results........
Am i missing something ? there should be 1 result ..I think but not sure right now ?
Thank you in advance
There are 7 instances of Interface having a foreign key to the Server having addres_ip='10.0.10.11' hence from the join (performed due to writing Interface__adress_ip='10.0.10.11') you get 7 (duplicated) objects / rows in the result.
Add a .distinct() at the end of your query, to remove the duplicate results:
Server.objects.filter(Q(adress_ip='10.0.10.11') | Q(Interface__adress_ip='10.0.10.11')).distinct()

How to get and update Django object in one query?

To optimize a lot my database I would like to make as less as possible any query.
I'm trying to get an object, increment the field "count_limit" and make an If statement after on the Customer instance.
To achieve it I've made this query who worked well.
Customer.objects.filter(user=user).update(count_limit=F('count_limit') + 1)
So after this query, count_limit has been incremented by 1 as I wanted.
When I'm trying to get the Customer instance as a result of this query, it returns "1".
Is it possible to make both, update the instance and get it as a return object ?
Thanks a lot
The update() method will return the number of updated rows. If you are using Postgres, then you can use the returning clause with the raw query.
query = 'UPDATE customer SET count_limit=(customer.count_limit + 1) WHERE customer.user_id=%s returning *'
updated_obj = Customer.objects.raw(query, [user.id])
I don't know if this can be achieved by ORM, but suggestions will be appreciated.
Make sure that the table name in raw query is correct. If you haven't definer db_table in the meta class of your model, then by default it will be myapp_model.
And to prevent SQL injection, from the Docs:
Do not use string formatting on raw queries or quote placeholders in
your SQL strings!
Follow Docs on raw()
You are looking for F functions: https://docs.djangoproject.com/en/3.0/ref/models/expressions/#f-expressions
Example from their documentation how to increase a counter
from django.db.models import F
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed = F('stories_filed') + 1
reporter.save()

How to get sql equivalent query from django query?

Currently I am developing website in Django & I need to convert some djnago query to sql equivalent query.
Purchase_order.objects.filter(query).order_by(id)[start: (start+length)]
I want to convert above django query into sql type of query.
Is there any way availble to convert it into sql also.
Yes. django does provides that feature. queryset comes with query object.
purchase_order = Purchase_order.objects.filter(query).order_by(id)[start: (start+length)]
print(purchase_order.query)
this will print corresponding query.

Django: performing a SQL match all in Django

I recently asked how to solve a simple SQL query. Turns out that there are many solutions.
After some benchmarking i think this is the best one:
SELECT DISTINCT Camera.*
FROM Camera c
INNER JOIN cameras_features fc1 ON c.id = fc1.camera_id AND fc1.feature_id = 1
INNER JOIN cameras_features fc2 ON c.id = fc2.camera_id AND fc2.feature_id = 2
Now, I've not clue how to perform this query with Django ORM.
If you need exactly this query you can execute this in django like raw sql. Here you can find about raw sql in django.
It`s good to put your sql code into a custom manager. An example with manager and raw sql can be found here

SQLAlchemy EXISTS queryset

I use only django framework with his ORM.
And there is some code:
User.objects.filter(username='test').exists()
that return True or False.
this orm query generate SQL:
SELECT (1) AS "a" FROM "auth_user" WHERE "auth_user"."username" = E'test' LIMIT 1
How I can perform equal query in SQLAlchemy?
I try understand this page
http://www.sqlalchemy.org/docs/05/ormtutorial.html#using-exists
but can't understand how this works.
Help please.
Thanks!
(ret,), = Session.query(exists().where(User.username=='test'))