TheNone
TheNone

Reputation: 5802

Extending Models In Django

I have a model like this:

class Model1(models.Model):
    .
    .
    .

and an extended model:

 class Model2(Model1):
    .
    .
    .

With this query:

model1 = Model1.objects.all()

How can I find items that belongs to inherited model (Model2) with above query?

Edit: I want to access this query from Model1:

class Model1(models.Model):
      def is_model2(self):
         m2 = self.objects.filter(model2__isnull=False)
             if m2.count() > 0:
                if self in m2:
                    return True
                else:
                    return False

Thanks in advance

Upvotes: 1

Views: 12511

Answers (2)

mkriheli
mkriheli

Reputation: 1846

You can also use InheritanceManager from django-model-utils. It'll return the correct instances, even when querying the base model.

Upvotes: 2

Mike DeSimone
Mike DeSimone

Reputation: 42805

Assuming Model1 doesn't have class Meta: abstract = True, this is multi-table inheritance.

You could use:

model2 = Model2.objects.all()

since all Model2 objects are Model1, or you could go through your query one at a time:

for m in model1:
    try:
        m.model2 # Try to use the Model2 object
    except Model2.DoesNotExist:
        pass

Or filter the query:

q = model1.filter(id__in=Model2.objects.all())

It's hard to tell which option is best from what little you give us.

EDIT: If you just want a function to tell you if a Model1 is a Model2, then you just need:

class Model1(models.Model):
    def is_model2(self):
        try:
            self.model2
        except Model2.DoesNotExist:
            return False
        return True

Upvotes: 1

Related Questions