gpt4 book ai didi

Django 嵌套序列化程序

转载 作者:行者123 更新时间:2023-12-05 03:39:05 26 4
gpt4 key购买 nike

我是 DRF/Django 的新手,我想创建一个端点,该端点以以下格式从多个模型返回嵌套的 json:

    { 
"site": {
"uuid": "99cba2b8-ddb0-11eb-bd58-237a8c3c3fe6",
"domain_name": "hello.org"
},

"status": "live",

"configuration": {
"secrets": [
{
"name": "SEGMENT_KEY", # Configuration.name
"value": [...] # Configuration.value
},
{
"name": "CONFIG_KEY",
"value": [...]
},

"admin_settings": {
'tier'='trail',
'subscription_ends'='some date',
'features'=[]
}

模型如下:

class Site(models.Model):
uuid = models.UUIDField(
default=uuid.uuid4,
editable=False,
unique=True)
domain_name = models.CharField(max_length=255, unique=True)
created = models.DateTimeField(editable=False, auto_now_add=True)
modified = models.DateTimeField(editable=False, auto_now=True)

class AdminConfiguration(models.Model):
TRIAL = 'trial'
PRO = 'pro'
TIERS = [
(TRIAL, 'Trial'),
(PRO, 'Professional'),
]
site = models.OneToOneField(
Site,
null=False,
blank=False,
on_delete=models.CASCADE)
tier = models.CharField(
max_length=255,
choices=TIERS,
default=TRIAL)
subscription_ends = models.DateTimeField(
default=set_default_expiration)
features = models.JSONField(default=list)


class Configuration(models.Model):
CSS = 'css'
SECRET = 'secret'
TYPES = [
(CSS, 'css'),
(SECRET, 'secret')
]
LIVE = 'live'
DRAFT = 'draft'
STATUSES = [
(LIVE, 'Live'),
(DRAFT, 'Draft'),
]
site = models.ForeignKey(Site, on_delete=models.CASCADE)
name = models.CharField(max_length=255, blank=False)
type = models.CharField(
max_length=255,
choices=TYPES)
value = models.JSONField(
null=True)
status = models.CharField(
max_length=20,
choices=STATUSES)

序列化器/ View 集背后的逻辑以实现提到的 json:

  • 检索lookup_field:uuid
  • 过滤器查询参数:Configuration.status(livedraft
  • 根据站点 ID 过滤 AdminConfiguration(类似于 AdminConfiguration.objects.get(Site.objects.get(uuid))
  • type = secret 上过滤配置

这是我的序列化程序:

class SiteSerializer(serializers.ModelSerializer):
class Meta:
model = Site
fields = [
'uuid',
'domain_name'
]

class AdminSerializer(serializers.ModelSerializer):
class Meta:
model = AdminConfiguration
fields = [
'tier',
'subscription_ends',
'features'
]

class ConfigurationSubSerializer(serializers.ModelSerializer):
class Meta:
model = Configuration
fields = [
'name',
'value',
]

class SecretsConfigSerializer(serializers.ModelSerializer):
site = SiteSerializer()
admin_settings = AdminSerializer()
status = serializers.CharField()
configuration = ConfigurationSubSerializer(many=True, source='get_secret_config')

class Meta:
model = Configuration
fields = [
'site',
'admin_settings',
'status'
'configuration'
]

def get_secret_config(self, uuid):
site = Site.objects.get(uuid=self.context['uuid'])
if self.context['status'] == 'live' or self.context['status'] == 'draft':
return Configuration.objects.filter(
site=site,
status=self.context['status'],
type='secret'
)

View 集:

class SecretsViewSet(viewsets.ReadOnlyModelViewSet):
model = Site
lookup_field = 'uuid'
serializer_class = SecertsConfigSerializer
filter_backends = (DjangoFilterBackend,)
filterset_fields = ['status'] #query params

def get_serializer_context(self):
return {
'status': self.request.GET['status'],
'uuid': self.request.GET['uuid']
}

def get_serializer(self, *args, **kwargs):
kwargs['context'] = self.get_serializer_context()
return CombinedConfigSerializer(*args, **kwargs)

要达到预期的输出,我还缺少什么?

  • django shell 的输出:
from site_config.models import Site, AdminConfiguration, Configuration
from site_config.serializers import SecretsConfigSerializer

site = Site.objects.get(id=2)
s = SecretsConfigSerializer(site)
s.data

### OUTPUT ###
AttributeError: Got AttributeError when attempting to get a value for field `site` on serializer `SecretsConfigSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Site` instance.
Original exception text was: 'Site' object has no attribute 'site'.

最佳答案

为什么你不尝试更通用的东西并像这样构建你的响应来分离序列化程序(也许你可以在其他地方使用相同的序列化程序):

def get(self, request, *args, **kwargs):
resp = {
'site': None,
'status': None,
'configuration': None,
'admin_settings': None,
}
sites = models.Site.objects.all()
resp['site'] = serializers.SitesSerializer(sites, many=True).data
admin_settings = models.AdminConfiguration.objects.all()
resp['admin_settings'] = serializers.AdminConfigurationSerializer(admin_settings, many=True).data
# and so
return Response(resp, status=status.HTTP_200_OK)

关于Django 嵌套序列化程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68718993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com