Skip to content

Custom Query with NestedField not behaving as expected #91

@bailey-heit

Description

@bailey-heit

Let's say we have 2 tables and a many_to_many table: \

product

| id | name | ...  | 
_________________________
| 4 | paper | ... | 
| 5 | string | ... | 
| 6 | water | ... | 
| 7 | paint |  ... | 

customer

| id | name | ... | 
_________________________
| 11 | bobby | ... | 
| 12 | sally | ... | 
| 13 | billy | ... | 
| 14 | joel |  ... | 

product_2_customer

id | c_id | p_id|
_________________________
108 | 4 | 11 | 
109 | 4 | 12 |
117 | 5 | 13 | 
119 | 6 | 13 | 
120 | 7 | 13 | 

Our Product Serializer looks something like:

class ProductSerializer(NestedModelSerializer):
        ... 
        customers = NestedField(CustomerSerializer, required=False, many=True, create_ops=["add"], update_ops=["add", "remove"])

Our Customer Model looks something like:

class Product():
         name = models.CharField(max_length=128)
         ...
         customers = models.ManyToManyField('Person', through="TreatmentRun2Person", blank=True)

When we run a default query on products, we get the expected results. For example, the customer object with id=13 associated with product id=5 is correctly returned.

 { 
...
    "customers": [
                {
                    "id": 13,
                    "first_name": "billy",
                    "last_name": "jean"
                }
            ],
...
}

However, when we run a custom query, ie /api/products/?&query={attributes,created_at,persons{id,first_name,last_name},suppliers{id,name}} then for product 5, the customer object returned is 13 repeated 3 times (for each time it's associated with a product). Better demonstrated:

 { 
...
    "customers": [
                {
                    "id": 13,
                    "first_name": "billy",
                    "last_name": "jean"
                },
                {
                    "id": 13,
                    "first_name": "billy",
                    "last_name": "jean"
                },
               {
                    "id": 13,
                    "first_name": "billy",
                    "last_name": "jean"
                }
            ],
...
}

This is not the behavior we would expect and we were wondering why the behavior changes when the query filter is applied? Thank you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions