【问题标题】:How to show up a new field in a django Model Serializer?如何在 django 模型序列化器中显示一个新字段?
【发布时间】:2021-04-08 23:54:33
【问题描述】:

我创建了不同的模型序列化器,例如 LocationDetailSerializer、ListingDetialSerializer 等。 他们的每个模型都与 PropertySerializer 的模型共享 OneToOne 关系。

属性模型:

class Property(models.Model):

# ? Relationships

user = models.ForeignKey(
    settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)

# ? Fields
property_unique_hash_id = models.UUIDField(
    default=uuid.uuid4, editable=False
)
.
.
.
.

created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)

def __str__(self):
    return "Property " + str(self.pk)

ListingDetial 模型:

class ListingDetial(models.Model):

# ? Relationships
property = models.OneToOneField("properties.Property", 
           on_delete=models.CASCADE)


listing_property_type = models.PositiveSmallIntegerField(
    choices=choices.LISTING_PROPERTY_TYPE,
    default=choices.LISTING_PROPERTY_TYPE.single_family_detached,
)
.
.
.
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)

def __str__(self):
    return "Listing Detail" + str(self.pk)

PropertySerializer:

class PropertySerializer(serializers.ModelSerializer):

# location_detail = LocationDetailSerializer()
# listing_detial = ListingDetialSerializer()
.
.
.
.
.
class Meta:
    model = Property
    fields = "__all__"

PropertySerializer 中,我还想要诸如 location_detail、listing_details 之类的字段,以便它可以与视图一起传递。

如何实现?

【问题讨论】:

  • 添加您的模型
  • @JPG 模型添加
  • 您好,您的问题不是很清楚,请问您的模型中的location_detail && listing_details 是从哪里来的?什么是 LocationDetailSerializer && LocationDetailSerializer?
  • @BriseBalloches 感谢您的回复,实际上我已经将大属性模型分解为不同的模型。这些模型中的所有列实际上都应该是属性模型的一部分。我认为创建不同的模型(如 LocationDetail 等)将使字段的组织变得容易。基于这些单独的模型序列化器,如 LocationDetailSerializer,LocationDetailSerializer 被创建。你认为打破这些模型是个好主意吗?如果是,那么如何使用 PropertySerializer 从不同的 Serilizer 填充这些字段?
  • 这里很难给你一个明确的答案。如果您认为它们应该被视为不同的对象,因为您将单独操作它们,那么是的,这是一个很好的设计,如果不是,那么可能将它们全部放在同一个模型中。对于 DRF 中的序列化关系,您应该首先查看 django-rest-framework.org/api-guide/relations,如果这没有帮助,请准确描述您期望的序列化程序的行为。

标签: django django-models django-rest-framework django-serializer


【解决方案1】:

这就是我让它工作的方式:

class PropertySerializer(serializers.ModelSerializer):

locationdetail = LocationDetailSerializer()
listingdetial = ListingDetialSerializer()
.
.
class Meta:
    model = Property
    fields = "__all__"

这将通过以下方式给出 json:

{
"id": 3,
"locationdetail": {
    "id": 3,
    "property": 3
    .
    .
    "created": "2021-01-03T01:53:58.987287Z",
    "last_updated": "2021-01-03T01:53:58.987287Z",


},
"listingdetial": {
    "id": 3,
    "property": 3
    .
    .
    "created": "2021-01-03T01:53:58.873135Z",
    "last_updated": "2021-01-03T01:53:58.873135Z",
    
},
}

【讨论】:

    猜你喜欢
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多