1

I would like to alter this query to return a RELATED field:

msgs = my_unit.messages_in_the_queue.all().select_related("message_content__description")

However,

>>> msgs.values()[0]
{... 'message_type_id': 31, 'object_id': 4, ...} # <--where is the "description"??

and

>>> msgs.values("message_content__description")[0]
FieldError: Cannot resolve keyword 'message_content__description' into field. Choices are: acknowledged_time, id, message_type, object_id, sent_time, destination

So far the only solution I found was to manually use this:

for queued_message in MyUnit.messages_in_the_queue.all().select_related():
    do_something_with(queued_message.message_content.description)

However, this is not a QuerySet and therefore NOT pageable - Is there a way to make it into a pageable query that returns the desired related field?

Here are the models:

class MessageQueueModel(models.Model):
    destination = models.ForeignKey(MyUnit, related_name="messages_in_the_queue")
    sent_time = models.DateTimeField(default=None, null=True, blank=True)
    acknowledged_time = models.DateTimeField(default=None, null=True, blank=True)

    #the message:
    message_type = models.ForeignKey(ContentType, null=True, blank=True)
    object_id = models.PositiveIntegerField(null=True, blank=True)
    message_content = generic.GenericForeignKey('message_type', 'object_id')


class CommandModel(models.Model):
    description = models.CharField(max_length=100)
    command_xml = models.TextField()

Any help would be much appreciated!

1 Answer 1

0

That's not how select_related works. You can't ask for a specific field to be added, just a relationship.

And it's not how values() works either: if you want the joined field to be added to your list of values, you need to ask for it in the list of fields.

Finally, it's also not how generic relations work. You can't join across a generic relation, because it's not really a foreign key.

However both of those things said, I don't understand what is wrong with your original queryset. What do you actually want to "page", and why is the queryset you got originally not suitable? (And, of course, why do you think that you can't paginate a normal list?)

2
  • Can you provide an example of hpw to make it so that using obj.message_content.description in the template doesn't access the database every time? I thought this is what select_related is for, but I may be confused..
    – Nimo
    Jan 23, 2013 at 15:10
  • 1
    Yes but select_related doesn't work for generic relationships. prefetch_related does - although again you want prefetch_related('message_content'). Jan 23, 2013 at 15:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.