我的 Django Restframework 中有兩個模型。在我看來,我想獲取所有屬性,并且對于每個屬性,我都會獲取創建它的用戶的個人資料資料。
我怎樣才能做到這一點?
例子:
#models.py
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
mobile = models.CharField(max_length=200)
location = models.CharField(max_length=200)
class Properties(models.Model):
title = models.CharField(max_length=200)
price = models.CharField(max_length=200)
category = models.CharField(max_length=200)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
#serializers.py
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = '__all__'
class PropertySerializer(serializers.ModelSerializer):
class Meta:
model = Property
fields = [
'title','price','category','created_by'
]
#views.py
class PropertiesView(generics.ListAPIView):
serializer = PropertySerializer
queryset = Property.objects.all()
uj5u.com熱心網友回復:
嘗試:
如果您想要完整的個人資料資料,那么 -
首先在屬性模型(createby 欄位)中定義相關名稱,例如 -
class Profile(models.Model):
---
---
class Properties(models.Model):
---
created_by =
models.ForeignKey(User, on_delete=models.CASCADE, related_name = "abc")
然后在序列化程式中使用相關名稱,并將其包含在諸如 -
class PropertySerializer(serializers.ModelSerializer):
abc = ProfileSerializer()
class Meta:
model = Property
fields = [
'title','price','category','created_by', 'abc'
]
如果您想要特定的個人資料資料,那么 -
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = '__all__'
class PropertySerializer(serializers.ModelSerializer):
mobile = serializers.SerializerMethodField()
class Meta:
model = Property
fields = [
'title','price','category','created_by', "mobile",
]
def get_mobile(self, instance):
return instance.created_by.mobile if instance.created_by else ''
uj5u.com熱心網友回復:
如果您想在您的屬性中獲取組態檔資料,請檢查以下內容 -
class PropertySerializer(serializers.ModelSerializer):
mobile = serializers.SerializerMethodField()
location = serializers.SerializerMethodField()
class Meta:
model = Property
fields = [
'title','price','category','created_by', "mobile", "location"
]
def get_mobile(self, instance):
return Profile.objects.get(user = instance.created_by).mobile
def get_location(self, instance):
return Profile.objects.get(user = instance.created_by).location
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/422712.html
標籤:
