如何将自定义注解字段转储到JSON fixture(Django)

1wnzp6jl  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(135)

我想改变令牌领域的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)

vojdkbi0

vojdkbi01#

也许它会帮助某人。
我使用了这个(继承自django.core.serializers.json.Serializer并重写get_dump_object()方法):

from django.core.serializers.json import Serializer as JSONSerializer

class CustomSerializer(JSONSerializer):
    def get_dump_object(self, obj):
        data = super().get_dump_object(obj)
        data["fields"]["facebook_token"] = obj.facebook_token
        data["fields"].pop("token")
        return data

字符串

相关问题