0

I've got two models in a Django application that have exactly the same fields, but different types of information is stored in each.

For example:

class A(models.Model)
    field_a =  models.CharField(primary_key = True, max_length = 24)
    field_b =  models.CharField(primary_key = True, max_length = 24)

class B(models.Model)
    field_a =  models.CharField(primary_key = True, max_length = 24)
    field_b =  models.CharField(primary_key = True, max_length = 24)

It seems like it would make sense to contain these in an abstract model and have these two classes as sub-classes. I was assuming that I could simply do this, without needing to make DB modifications, but Django isn't able to find the fields of my models any longer.

Could someone offer advice?

james_dean
  • 1,477
  • 6
  • 26
  • 37

1 Answers1

2

If you create a new abstract class this won't interfere with your database. As you can see in documentation https://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes abstract classes are just python classes without database impact.

your code could be looks like this:

class Parent(models.Model)
    field_a =  models.CharField(primary_key = True, max_length = 24)
    field_b =  models.CharField(primary_key = True, max_length = 24)

    class Meta:
        abstract = True

class A(Parent)
    pass

class B(Parent)
    pass
andyinno
  • 1,021
  • 2
  • 9
  • 24
  • I tried this originally but receive a 'Exception Type: FieldError' – james_dean Mar 01 '13 at 16:02
  • 1
    maybe the problem is in some details of what you did? maybe you mispelled something? Actually this is the way for implement this kind of thing. If you can try it again could be really useful to know the exact error you get and maybe try to solve it. – andyinno Mar 01 '13 at 16:13
  • This should indeed work just fine, btw if you require a non abstract way to reuse data subclassing queryset is a great way to create a [generic approach](http://stackoverflow.com/questions/349206/how-do-i-find-the-concrete-class-of-a-django-model-baseclass) – Hedde van der Heide Mar 01 '13 at 16:18