Django query in One to Many relationship

jalanga

I have 2 tables, Order and OrderDetails, on OrderDetails I have a field 'product_type'.

From the table Order I want to get all the product_type fields in a list.

Order.objects.filter(pk=1).annotate(type=F('product_type'))

I want the type value to return a list of all product types, not just the first result like 'chair'.

Ex: type = ['chair', 'pencil']

Models:

class Order(models.Model):
    user = models.ForeignKey(User, related_name="orders")

class OrderDetails(models.Model):
    order = models.ForeignKey(Order, related_name="details")
    quantity = models.SmallIntegerField(null=False, blank=False)
    product_type = models.CharField(null=False, blank=False)
Anentropic

This is not something you can or should try to achieve with a queryset annotation. This is because annotations are only usable for aggregation functions like Count, Sum etc.

If I understood your question correctly, you can get this info when iterating over the queryset:

for order in Order.objects.all():
    types = order.details.values_list('product_type', flat=True)

You can make this more efficient by prefetching the related OrderDetail rows for each order:

for order in Order.objects.prefetch_related('details'):
    types = order.details.values_list('product_type', flat=True)

Alternatively, you can retrieve some values from each order using this method:

queryset = Order.objects.values('id', 'user_id', 'details__product_type')

It should do a single db query. However, see the notes here about how this works: https://docs.djangoproject.com/en/1.9/ref/models/querysets/#values

Your queryset will output dicts instead of model instances. And you will not get a nice list of product_types... instead you will get repeated rows like:

[
    {'id': 1, 'user_id': 1, 'product_type': 'chair'},
    {'id': 1, 'user_id': 1, 'product_type': 'table'},
    {'id': 2, 'user_id': 3, 'product_type': 'chair'},
    ...
]

...so you'll then have to group these rows in python into the data structure you want:

from collections import OrderedDict

grouped = OrderedDict()
for order in Order.objects.values('id', 'user_id', 'details__product_type'):
    if order['id'] not in grouped:
        grouped[order['id']] = {
            'id': order['id'],
            'user_id': order['user_id'],
            'types': set(),
        }
    grouped[order['id']]['types'].add(order['details__product_type'])

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Django one to many Relationship Query

From Dev

Django: Query one to many relationship for existing relationship with certain attributes in the many-model

From Dev

Query One to Many Relationship SQLAlchemy

From Dev

JPA one to many relationship query

From Dev

Query One to Many Relationship SQLAlchemy

From Dev

CoreData: Query to one-to-many-to-many relationship

From Dev

ios parse one query many to many relationship

From Dev

How to query a one to many/many to many relationship in Flask SQL Alchemy?

From Dev

Is there a way to simplify a Linq query with a many to one relationship?

From Dev

Criteria query for unidirectional one-to-many relationship

From Dev

jooq single query with one to many relationship

From Dev

Data base One To Many Relationship Query

From Dev

Data base One To Many Relationship Query

From Dev

How to query one-to-many relationship in JPQL?

From Dev

Is there a way to simplify a Linq query with a many to one relationship?

From Dev

query regarding one to many relationship in hibernate

From Dev

Criteria query for unidirectional one-to-many relationship

From Dev

Query two tables with one to many relationship

From Dev

Ruby on Rails Query a one to many relationship

From Dev

Django one to many relationship: number of objects

From Dev

Django Form with a one-to-many relationship

From Dev

Better Django UI for one to many relationship

From Dev

Django displaying one to many relationship in the admin page

From Dev

Django Many-To-One relationship filter set

From Dev

Serializing One to Many Relationship in django REST framework

From Dev

Django, Many-to-one relationship with Abstract entities

From Dev

Django Form with a one-to-many relationship

From Dev

Django one to many relationship: number of objects

From Dev

creating a many to one relationship in django with an existing model

Related Related

  1. 1

    Django one to many Relationship Query

  2. 2

    Django: Query one to many relationship for existing relationship with certain attributes in the many-model

  3. 3

    Query One to Many Relationship SQLAlchemy

  4. 4

    JPA one to many relationship query

  5. 5

    Query One to Many Relationship SQLAlchemy

  6. 6

    CoreData: Query to one-to-many-to-many relationship

  7. 7

    ios parse one query many to many relationship

  8. 8

    How to query a one to many/many to many relationship in Flask SQL Alchemy?

  9. 9

    Is there a way to simplify a Linq query with a many to one relationship?

  10. 10

    Criteria query for unidirectional one-to-many relationship

  11. 11

    jooq single query with one to many relationship

  12. 12

    Data base One To Many Relationship Query

  13. 13

    Data base One To Many Relationship Query

  14. 14

    How to query one-to-many relationship in JPQL?

  15. 15

    Is there a way to simplify a Linq query with a many to one relationship?

  16. 16

    query regarding one to many relationship in hibernate

  17. 17

    Criteria query for unidirectional one-to-many relationship

  18. 18

    Query two tables with one to many relationship

  19. 19

    Ruby on Rails Query a one to many relationship

  20. 20

    Django one to many relationship: number of objects

  21. 21

    Django Form with a one-to-many relationship

  22. 22

    Better Django UI for one to many relationship

  23. 23

    Django displaying one to many relationship in the admin page

  24. 24

    Django Many-To-One relationship filter set

  25. 25

    Serializing One to Many Relationship in django REST framework

  26. 26

    Django, Many-to-one relationship with Abstract entities

  27. 27

    Django Form with a one-to-many relationship

  28. 28

    Django one to many relationship: number of objects

  29. 29

    creating a many to one relationship in django with an existing model

HotTag

Archive