0

I was wondering if it could be possible to query a Django model using aliases of its fields?

for exemple:

class Book(models.Model):
    pub_date = models.DateTimeField(_('Publication Date'),
    ...

class Magazine(models.Model):
    creation_date = models.DateTimeField(_('Publication Date'),
    ...

I can alias the class, which is great:

my_class = Book

then query it as:

my_class.objects.all()

Fine!

I would like to be able to alias the Book.pub_date & Magazine.creation_date as my_pub_date, so I could do:

Book.objects.filter(my_pub_date__gt=some_date) (or my_class.objects.filter(my_pub_date__gt=some_date))

instead of:

Book.objects.filter(pub_date__gt=some_date)

Thanks

1
  • 3
    It may well be doable, but I think it's probably more trouble than it's worth. How about adding a Book.get_published_after_queryset classmethod? You could do similar methods on Magazine, etc, and then just call my_class.get_pushed_after_queryset(some_date).filter(...). Commented Mar 14, 2012 at 12:29

1 Answer 1

3

Not without a whole lot of effort. And even if it were possible, don't do that if you want to keep your sanity.

In this case I'd use (a) an abstract base class which holds the common information for both models.

class Publication(models.Model):
    pub_date = models.DateField(_('publication date'))
    # other fields

    class Meta:
        abstract = True

class Book(Publication):
    # ...

class Magazine(Publication):
    # ...

Or (b) a single model with a publication_type field, with choices "book" and "magazine".

Or (c) add custom Managers and QuerySets to both models with a method published_after that knows which attribute to use for the filter.

I suggest picking (b) if there's not a lot of difference between books and magazines and (a) if there is.

Sign up to request clarification or add additional context in comments.

1 Comment

(c) seems to be the best match with my goal. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.