我的问题是如何获取整个对象而不是外键。 请参阅下面的代码和输出,以便您了解我的问题
这些是我的models.py
班级教授(models.Model):professor_id = models.AutoField(primary_key=True, auto_created=True)
name = models.CharField(max_length=256)
email = models.CharField(max_length=256)
mobile = models.CharField(max_length=256)
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
class Preference(models.Model):
preference_id = models.AutoField(primary_key=True, auto_created=True)
professor = models.ForeignKey('Professor', on_delete=models.CASCADE)
rank = models.IntegerField()
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
这些是我的views.py
类CreateListMixin:
def get_serializer(self, *args, **kwargs):
if isinstance(kwargs.get('data', {}), list):
kwargs['many'] = True
return super().get_serializer(*args, **kwargs)
class PreferenceViewSet(CreateListMixin,viewsets.ModelViewSet):
queryset = Preference.objects.all()
serializer_class = PreferenceSerializer
这是我的serializers.py
class PreferenceSerializer(serializers.ModelSerializer):
class Meta:
model = Preference
我的输出为
[
{
"preference_id": 1,
"rank": 1,
"professor": Eshwar
"created_at": "2018-01-13T00:00:00Z",
"updated_at": "2018-01-13T00:00:00Z"
}
如果我必须将教授的详细信息作为对象,该怎么办:
[
{
"preference_id": 1,
"rank": 1,
"professor": {
professor_id = 1
name = Eshwar
email = ....
mobile = ....
created_at = ...
updated_at = ....
}
"created_at": "2018-01-13T00:00:00Z",
"updated_at": "2018-01-13T00:00:00Z"
}
我的问题是如何获取整个对象而不是外键
感谢任何帮助。
答案 0 :(得分:0)
使用serializer
模型
Professor
class PreferenceSerializer(serializers.ModelSerializer):
professor = ProfessorSerializer()
class Meta:
model = Preference
fields = ['other_fields','professor']