1

I am using django(1.9)-python(2.7) for my project where my models are created from legacy db (Oracle) using inspectdb. The problem here is the legacy db has composite primary keys.

My approach to the problem in question was usage of Composite fields http://django-composite-field.readthedocs.io/en/latest/

from composite_field import CompositeField

class Thing(models.Model):
    first = models.CharField(max_length=32)
    second = models.IntegerField()
    both = CompositeField(('first', 'second'))

But I end up in the following error ...

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "<console>", line 4, in Thing
  File "C:\Python27\Lib\site-packages\composite_field\base.py", line 70, in __in
it__
    self.subfields = deepcopy(self.subfields)
AttributeError: 'CompositeField' object has no attribute 'subfields'

Thanks in advance!!

  • It would be much better if you posted the full stacktracce – e4c5 Jun 15 '16 at 10:20
  • Please also see this answer. http://stackoverflow.com/a/37716599/267540 – e4c5 Jun 15 '16 at 10:48
  • I already use the unique_together solution but when accessing the table I get into ORA-0094 (id invalid identifiert) as python by default creates a primary key by name id and this identifier is not present in database. I want to use the existing schema rather make changes to it. – Sruthi Subramanyam Jun 15 '16 at 13:11
  • python does not create any primary keys. Django creates a primary key if you don't define one. If you read that answer fully you will understand things better – e4c5 Jun 15 '16 at 13:26
  • Yes, I stand corrected. django creates primary key if I don't define one. I have read through the article and it suggests to change the schema, which in my case I am not allowed to do so. Hence, I wanted to use Composite Field as an alternative, where I can declare composite field with multiple fields and use this as a primary key. – Sruthi Subramanyam Jun 15 '16 at 14:12

1 Answers1

1

Use django-composite-field from here.

Example usage is as follows:

class CoordField(CompositeField):
    x = models.FloatField()
    y = models.FloatField()

class Place(models.Model):
    name = models.CharField(max_length=10)
    coord = CoordField()

p = Place(name='Foo', coord_x=42, coord_y=0)
q = Place(name='Foo', coord=p.coord)
q.coord.y = 42

(copied from the official documentation)

Amir
  • 2,259
  • 1
  • 19
  • 29