【问题标题】:When I click on the save button it will check that data on the database before saving it in Django?当我单击保存按钮时,它会在将其保存到 Django 之前检查数据库中的数据吗?
【发布时间】:2021-06-19 06:53:39
【问题描述】:

当我点击保存按钮时,它会在将数据保存到 Django 之前检查数据库中的数据。在 Django 管理中插入之前在数据库中搜索数据。我不想保存已经保存在数据库中的相同数据。

像这样: 在这里首页保存加倍。但我希望如果家庭已经保存,那么我第二次尝试保存同名时它不会保存。 如何编码?

models.py

class Brand(models.Model):
    brand_id = models.id = models.AutoField(primary_key=True, auto_created=True)
    brand_name = models.CharField(max_length=50)
    brand_date = models.DateTimeField(auto_now_add=True, null=False)

【问题讨论】:

  • unique=True 添加到brand_name。你也不需要广告brand_id,你的数据库中的每个对象都会有一个自动ID字段
  • 谢谢,@hansTheFranz 我是 python 新手。所以我还在学习。

标签: python mysql django django-models


【解决方案1】:

如果您想要一个唯一的字段,请使用 unique=True

由于您是 python 新手,以下技巧将来会派上用场

假设您希望字段组合是唯一的,您可以在 Meta 中添加约束

class Brand(models.Model):
    brand_name = models.CharField(max_length=255, index=True)
    brand_location = models.CharField(max_length=255, index=True)
    brand_date = models.DateTimeField(auto_now_add=True, null=False)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['brand_name', 'brand_location'], name='unique_brand')
        ]

现在每个位置您将只有一个唯一的品牌名称。

您可以从here阅读更多关于约束的信息

【讨论】:

    【解决方案2】:

    我想将unique=True 添加到brand_name

    brand_name = models.CharField(max_length=50, unique=True)
    

    【讨论】:

      【解决方案3】:

      您可以添加unique=True 以避免重复:

      brand_name = models.CharField(max_length=50, unique=True)
      

      【讨论】:

      • 我是 python 新手。所以我还在学习。谢谢@C14L
      猜你喜欢
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 2012-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多