简体   繁体   中英

Best way to set unique_together for all fields of a django model

I would like to prevent the creation of duplicated rows on some tables of my database. I know one way to do it is setting the unique_together or constraints attribute in the Meta class of the model as a tuple with the names of the fields, but I'd like to know if there's a better way to do it since my models have 30+ fields, so I don't think it would be practical to repeat the names of them again.

The way I have it now:

class MyModel(models.Model):
  model_id = models.BigAutoField(db_column="MyModelColumnID", primary_key=True)
  field1 = models.BooleanField(...)
  field2 = models.CharField(...)
  field3 = models. ...
  .
  .
  .
  field34 = models. ...
  
  class Meta:
    db_table = "MyTableName"
    unique_together = (
      "field1",
      "field2",
      "field3",
       .
       .
       .
       "field34"
    )
      

I'm looking for something like unique_together="__all__" or all_unique=True , is this possible on Django?

It is important to me to handle this as a database constraint, the get_or_create method won't suffice since it's for an app using multiple threads and making multiple concurrent calls to the database. Thanks !

I didn't find a way to do what I was looking for but I somehow managed to not repeat all the field names of the model by defining an abstract model and then using that one to get the fields. Like this:

class MyModelBase(models.Model):
  model_id = models.BigAutoField(db_column="MyModelColumnID", primary_key=True)
  field1 = models.BooleanField(...)
  field2 = models.CharField(...)
  field3 = models. ...
  .
  .
  .
  field34 = models. ...
  
  class Meta:
    abstract=True

class MyModel(MyModelBase):

  class Meta:
    db_table = "MyTableName"
    unique_together = tuple(
      [field.name for field in MyModelBase._meta.fields if field.name != "model_id"]
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM