我想改变令牌领域的facebook_token在夹具.我会很高兴,如果你帮我请
models.py
class FacebookAdAccounts(models.Model):
id_ad = models.CharField(max_length=255)
name_ad = models.CharField(max_length=255)
currency = models.CharField(max_length=255, default='USD')
is_active = models.BooleanField(default=True)
business_account = models.ForeignKey(FacebookBusinessAccounts, on_delete=models.CASCADE, blank=True, null=True)
token = models.CharField(max_length=510, blank=True, null=True)
def __str__(self):
return f'{self.id_ad} {self.name_ad} - {self.name_ad}'
class FacebookTokens(models.Model):
token = models.CharField(max_length=510)
user_id = models.CharField(max_length=255)
字符串
鉴于此模型,我想将FacebookAdAccounts模型的夹具转换为JSON格式。
我有这样的结果:
[
{
"model": "facebook.FacebookAdAccount",
"pk": 1,
"fields": {
"id_ad": "id_ad1",
"name_ad": "name_ad_1",
"currency": "USD",
"is_active": true,
"business_account": null,
"token": "TOKEN_USER#1"
},
...
]
型
我希望这个结果:
[
{
"model": "facebook.FacebookAdAccount",
"pk": 1,
"fields": {
"id_ad": "id_ad1",
"name_ad": "name_ad_1",
"currency": "USD",
"is_active": true,
"business_account": null,
"facebook_token": 4
},
...
]
型
我试过这个:
FacebookAdAccounts._meta.model_name = "FacebookAdAccount" FacebookAdAccounts._meta.app_label = "facebook"
subquery = FacebookTokens.objects.filter(token=OuterRef("token")).values("pk")[:1]
**queryset = FacebookAdAccounts.objects.annotate( facebook_token=Subquery(subquery) ) # I want facebook_token field to also be serialized**
json_data = serializers.serialize("json", queryset, indent=4)
file_path = "data2.json"
with open(file_path, "w") as file: file.write(data)
型
1条答案
按热度按时间vojdkbi01#
也许它会帮助某人。
我使用了这个(继承自django.core.serializers.json.Serializer并重写get_dump_object()方法):
字符串