I have two models
class A(models.Model):
name = models.CharField(max_length=32)
...
class B(models.Model):
fkey = models.ForeignKey("A", on_delete=models.CASCADE)
...
I want to create queryset of objects A based on condition if some of B objects is referring to A in my DRF serializer
a1 = A.objects.create(name="1")
a2 = A.objects.create(name="2")
b1 = B.objects.create(fkey=a1)
a_objs = A.objects.filter()
serializer = ASerializer(a_objs, many=True)
serializer.data
{
{
"name": "1"
},
"b_attached": true
},
{
{
"name": "2"
},
"b_attached": false
}
What is the best way to achieve this?
CodePudding user response:
You'r response is an invalid json!
you can use nested serialization to achieve something like this:
from rest_framework import serializers
from .models import A, B
class ADetailSerializer(serializers.ModelSerializer):
class Meta:
model = A
fields = ("name",)
class ASerializer(serializers.ModelSerializer):
A_OBJ = serializers.SerializerMethodField(method_name='get_a_obj')
b_attached = serializers.SerializerMethodField(method_name='get_b_attached')
class Meta:
model = A
fields = ("A_OBJ", "b_attached")
def get_b_attached(self, obj):
if obj.b_set.exists():
return True
return False
def get_a_obj(self, obj):
return ADetailSerializer(obj, many=False).data
and the response will be:
[
{
"A_OBJ": {
"name": "1"
},
"b_attached": true
},
{
"A_OBJ": {
"name": "2"
},
"b_attached": false
}
]