Я использую django rest framework для создания REST API. Моя модель содержит одно поле «многие ко многим», и я сталкиваюсь с некоторыми сложностями при его сериализации.
models.py
class CustomerMaster(models.Model):
customer_key = models.IntegerField(db_column='CUSTOMER_KEY', primary_key=True) # Field name made lowercase.
first_name = models.TextField(db_column='FIRST_NAME', blank=True, null=True) # Field name made lowercase.
last_name = models.TextField(db_column='LAST_NAME', blank=True, null=True) # Field name made lowercase.
email = models.CharField(db_column='EMAIL', max_length=255, blank=True, null=True) # Field name made lowercase.
gender = models.TextField(db_column='GENDER', blank=True, null=True) # Field name made lowercase.
dob = models.DateField(db_column='DOB', blank=True, null=True) # Field name made lowercase.
phone = models.CharField(db_column='PHONE', max_length=255, blank=True, null=True) # Field name made lowercase.
address = models.TextField(db_column='ADDRESS', blank=True, null=True) # Field name made lowercase.
...
class Meta:
managed = False
db_table = 'customer_master'
def __str__(self):
return self.first_name + self.last_name
class Segment(models.Model):
name = models.CharField(max_length=100)
folder = models.CharField(max_length=100)
selection = JSONField()
createdAt = models.DateTimeField(null=True)
updatedAt = models.DateTimeField(null=True)
createdBy = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
contact = models.ManyToManyField(CustomerMaster)
def __str__(self):
return self.name
Serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('pk', 'email', 'first_name', 'last_name',)
class CustomerEmailSerializer(serializers.ModelSerializer):
class Meta:
model = CustomerMaster
fields = ('email', )
class SegmentSerializer(serializers.ModelSerializer):
contact = CustomerEmailSerializer(many=True)
createdBy = UserSerializer(required=False)
class Meta:
model = Segment
fields = ('name', 'folder', 'selection', 'createdAt', 'updatedAt', 'createdBy', 'contact')
Вывод моего запроса GET:
{
"name": "asgg",
"folder": "Ticketing",
"selection": "{\"qq\": \"ee\"}",
"createdAt": null,
"updatedAt": null,
"createdBy": null,
"contact": [
{
"email": "aakashnihalani26@gmail.com"
},
{
"email": "qwerty@gmail.com"
}
]
}
Я хочу, чтобы мой вывод выглядел примерно так:
{
"name": "asgg",
"folder": "Ticketing",
"selection": "{\"qq\": \"ee\"}",
"createdAt": null,
"updatedAt": null,
"createdBy": null,
"contact": [
"aakashnihalani26@gmail.com",
"qwerty@gmail.com"
]
}
Я использую python 3.7, django 2.2.11, django rest рамки 3.11.0
Любая помощь будет оценена. Заранее спасибо!