簡體   English   中英

使用 Django 刪除對象 Delete

[英]Deleting Objects with Django Delete

我從我的數據庫中僅刪除一個 object 時遇到問題,我有一個代碼可以從 AWS 獲取 RDS 主機名列表,然后將存儲在我的數據庫中的 rds 主機名與 AWS 返回的主機名進行比較,如果 rds 主機名存儲在我的數據庫而不是由 AWS 返回它應該從我的數據庫中刪除,但我的代碼最終會刪除存儲在我的數據庫中的所有 RDS 主機名

這是我的模型


class AwsAssets(BaseModel):
    aws_access_token = models.CharField(max_length=512, blank=True, null=True)
    aws_secret_token = models.CharField(max_length=512, blank=True, null=True)
    rds_count = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return '{} - {}'.format(
        self.client_aws_access_token,
        self.client_aws_secret_token
        )

    class Meta:
        verbose_name_plural = "Aws Assets"


class AwsRdsNames(BaseModel):
    host = models.CharField(max_length=300, null=True, blank=True)
    port = models.IntegerField(null=True, blank=True)
    asset_link = models.ForeignKey(AwsAssets, null=True, blank=True,
        related_name="rds_endpoints", on_delete=models.CASCADE
    )
    region = models.CharField(max_length=56, null=True, blank=True)
    scan_status = models.NullBooleanField(default=None)
    last_scan = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return "{}:{}".format(self.host, self.port)

    class Meta:
        db_table = 'aws_rds_names'
        ordering = ['-id']


然后這里是負責刪除 rds 主機名的代碼塊

all_stored_rds = AwsRdsNames.objects.all()
stored_rds = all_stored_rds.filter(asset_link=self.asset) #This returns all the stored rds hosts  in db
aws_rds = get_rds() #This returns a list of rds hostname from aws

for rds in stored_rds:
     if rds.host not in aws_rds:
          AwsRdsNames.objects.filter(host=rds.host).delete()

此代碼最終刪除了存儲在我的數據庫中的所有 rds 主機,而不是刪除 aws 未返回的主機

假設您有一個包含現有域名稱的列表:

domains = ["domain1", "domain2", "domain3", ...]
for entry in AwsRdsNames.objects.all():
   if entry.host not in domains:
       entry.delete()

應該這樣做。

直接刪除:

SomeModel.objects.filter(id=id).delete()

要從實例中刪除它:

instance = SomeModel.objects.get(id=id)
instance.delete()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM