我有幾個模型將用戶作爲外鍵。例如,我有型號Profile
,型號profilePic
和型號userQuestions
- 在所有型號中,用戶都是外鍵。DRF - 將不同的模型序列化爲一個
有沒有一種方法可以得到一個profile
,profilePic
和userQuestions
對應於給定的用戶在一個單一的JSON響應?
我的models.py是繼
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
gender = models.CharField(max_length=2)
name = models.CharField(max_length=200)
birthday = models.DateField(auto_now=False, auto_now_add=False)
weight = models.IntegerField(default=0)
heigth = models.IntegerField(default=0)
sign = models.CharField(max_length=200, choices=SIGNS_CHOICES, default='E')
orientation = models.CharField(max_length=200, choices=ORIENTATION_CHOICES, default='E')
bodytype = models.CharField(max_length=200, choices=BODYTYPE_CHOICES, default='E')
education = models.CharField(max_length=200, choices=EDUCATION_CHOICES, default='E')
religion = models.CharField(max_length=200, choices=RELIGION_CHOICES, default='E')
smoking = models.CharField(max_length=200, choices=SMOKING_CHOICES, default='E')
alcohol = models.CharField(max_length=200, choices=ALCOHOL_CHOICES, default='E')
kids = models.CharField(max_length=200, choices=KIDS_CHOICES, default='E')
pets = models.CharField(max_length=200, choices=KIDS_CHOICES, default='E')
location = models.CharField(max_length=100)
latitude = models.FloatField()
longtitude = models.FloatField()
class ProfileFields(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
order = models.IntegerField(default=0)
class ProfilePic(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profilePic = models.ImageField(upload_to='Images/', default='Images/None/No-img.jpg')
class Pics(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
pic = models.ImageField(upload_to='Images/', default='Images/None/No-img.jpg')
UPD
嘗試添加
def to_representation(self, data):
profile_info = {kv: data[kv] for kv in data if kv in list(ProfileSerializer.Meta.fields)}
profile_pic_info = {kv: data[kv] for kv in data if kv in list(ProfilePicSerializer.Meta.fields)}
return super(DeviceInfoSerializer, self).to_representation({
'profile': profile_info,
'profile_pic': profile_pic_info,
})
,但現在它說對象 '用戶' 是不是可重複的
是的,但你必須張貼您的models.py – itzMEonTV
@itzmeontv做 –