Thats my models:
class Org:
name = CharField()
owner = ForeignKey(User)
class Cafe:
name = CharField()
org = ForeignKey(Org)
class Product:
name = CharField()
class Assortment:
cafe = ForeignKey(Cafe)
product = ForeignKey(Product)
price = IntegerField
So the deal is - i need to search products with very specific way. It should looks like this: /assortment/search/?searh=cola
'cafe':{
'id:1,
'name': 'Foo',
'assortment': [
{
'product': {
'id': 1,
'name': 'Cola'
},
'price': 100
},
{
'product': {
'id': 2,
'name': 'Coca-cola'
},
'price': 200,
}
],
'search_count': 5,
},
'cafe': {
'id':2,
'name': 'Bar',
'assortment': [
{
'product': {
'id': 3,
'name': 'Sprite-cola',
},
'price': 150,
},
]
'search_count': 1,
}
So the problem is - when i search like
Cafe.objects.filter(assortment__product__name='cola')
It works, it shows all Cafes where product with name 'cola' exists, but problem is DJF serializer
class CafeSerialzier:
assortments = AssortmentSerializer(source='assortment_set')
search_count = IntegerField(source='assortment_set.count')
assortments and search_count shows all assortment and count of it, and does not consider search arguments, which is expected. So the question is - how to pass search parameters into source='assortment_set' (Also i need to limit results to 3) and how to count all search results.
I've tried SerializerMethodField for assrotments, it solves a part of my problems but it causes a lot of queries.
Overriding of get_field method has the same problems.
So is there sane way to filter and limit queryset related field in ModelSerializer and get count of unlimited but filtered queryset of the same field?
You are trying to get assortment resource via:
/assortment/search/?search=colaso your response should not contain cafe resources, but assortment resources like this:You should create a
ListViewforAssortmentmodel with anAssortmentSerializer. Instead of usingCafe.objects.filter(assortment__product__name='cola')you will useAssortment.objects.filter(product__name='cola')in your search view (list view).