0

hi im having troubles in django 3.2 with a work arround for composite key's. as my customer request he needs a composite key as primary key not just on unique_together constraint so im wonder if there any way or place to intercept the instance be fore validation and populate the composite key with values from the other fields and save it to the db ej:

class MyModel(models.Model):
   foo = models.UUIDField(default=uuid.uuid4,
                          auto_created=True, editable=False, max_length=36)
   bar = models-charfield()
   taz = models.charfield()
   composite_key = models.charfield(primary_key=True, default = 'foo' + 'taz' + 'foo')

somthing among these lines i cant get pass from the form field validator on django admin site so i really cant test signals or save() method any help wil be apreciated.

Mikesiwi
  • 9
  • 1
  • Remove `default` in `composite_key` and override model save method by populating composite_key values with other fields. Override like this https://stackoverflow.com/questions/4269605/django-override-save-for-model – Ahtisham Dec 27 '21 at 20:43
  • ok its working now but i can create user just from comand line and i presume from views (witch i dont use) but from the admin site i cant by pass the "composite_key" required field – Mikesiwi Dec 28 '21 at 13:00

1 Answers1

0

Try this:

class MyModel(models.Model):
   foo = models.UUIDField(default=uuid.uuid4,
                          auto_created=True, editable=False, max_length=36)
   bar = models.charfield()
   taz = models.charfield()
   composite_key = models.charfield(primary_key=True)

   def save(self, *args, **kwargs):
      self.composite_key = self.foo
      if self.bar:
         self.composite_key += self.bar
      if self.taz:
         self.composite_key += self.taz
      super(Model, self).save(*args, **kwargs)
Ahtisham
  • 9,170
  • 4
  • 43
  • 57
  • i im really made my composite key working but in the admin site cant save be cause the form needs composite key before the save() so ints empty at the moment and cant pass the validation – Mikesiwi Dec 28 '21 at 14:03
  • In the form you can override the clean method just like you override save method and bypass the validation of composit key – Ahtisham Dec 29 '21 at 02:30