【发布时间】:2023-03-20 12:25:01
【问题描述】:
最近我开始使用 django 框架,我被困在这种情况下尝试阅读文档,但我缺乏经验,我不太了解有什么方法可以通过保持 django 默认检查和验证来获得我们想要的响应尽可能。我尝试使用 def to_representation 但在我调试时它仍然让我响应为 null。
用例: 我在下面提到了模型我希望外键值作为文本存储在产品表中的表 status_lookup.name 中
class product_serializer(serializers.ModelSerializer):
status = status_lookup_serializer(read_only=True,many=False)
class Meta:
model = product
fields = ('id','name','status_id','status')
模型.py
class status_lookup(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(blank=True)
activation_date = models.DateTimeField(auto_now_add=True)
deactivation_date = models.DateTimeField(blank=True,default=None)
def __str__(self):
return self.name
class product(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
img_url = models.CharField(max_length=255,blank=True)
status_id = models.ForeignKey(status_lookup, related_name='status', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(blank=True)
activation_date = models.DateTimeField(auto_now_add=True)
deactivation_date = models.DateTimeField(blank=True,default=None)
def __str__(self):
return self.name
我想要
[
{
"id":1,
"name":"xxx",
"status":pending
}
]
【问题讨论】:
标签: python-3.x django django-models django-rest-framework django-views