Domanda

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!

È stato utile?

Soluzione

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?)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top