【问题标题】:Updating Database via GET request to Generic views in Django通过 GET 请求更新数据库到 Django 中的通用视图
【发布时间】:2022-10-13 16:53:45
【问题描述】:

我有这个通用视图,它会列出我的数据库中针对GET 请求到localhost:8000 的记录但是,我还想在GET 上更新这些记录。例如,GETlocalhost:8000 将返回如下列表:

[
    {
        "user": 1,
        "address": "sdfgasgasdfg",
        "balance": "123.00000000"
    },
    {
        "user": 1,
        "address": "sdfgasgasdfg25",
        "balance": "123.00000000"
    }
]

在 GET 之后,我还想为 https://www.blockchain.com/api/blockchain_api 创建一个 API,以获取最新的 BTC 余额并更新我数据库中这些地址的余额值。不太确定如何使用通用视图执行此操作

看法

class WalletListCreateAPIView(generics.ListCreateAPIView):
    queryset = Wallet.objects.all()
    serializer_class = WalletSerializer

模型

class Wallet(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    address = models.CharField(max_length=34)
    balance = models.DecimalField(max_digits=16, decimal_places=8)
    slug = models.SlugField(max_length=34, blank=True, null=True)

    def __str__(self):
        return self.address

    def save(self, *args, **kwargs):
        self.slug = slugify(self.address)
        super().save(*args, **kwargs)

【问题讨论】:

    标签: python python-3.x django django-rest-framework


    【解决方案1】:

    我会覆盖 API 的 list(...) 方法(在 GET 请求中调用)

    class WalletListCreateAPIView(generics.ListCreateAPIView):
        queryset = Wallet.objects.all()
        serializer_class = WalletSerializer
    
        def pull_data_from_api_and_update_db(self):
            # do some stuff here
            pass
    
        def list(self, request, *args, **kwargs):
            self.pull_data_from_api_and_update_db()
            return super().list(request, *args, **kwargs)
    

    在这里,您可以按照自己的方式添加/更新 pull_data_from_api_and_update_db(...) 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 2016-04-05
      • 2019-11-28
      • 2016-07-19
      • 2022-09-24
      相关资源
      最近更新 更多