Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango query — how to get list of dictionaries with M2M relation?
    primarykey
    data
    text
    <p>Let's say, I have this simple application with two models — <code>Tag</code> and <code>SomeModel</code></p> <pre><code>class Tag(models.Model): text = ... class SomeModel(models.Model): tags = models.ManyToManyField(Tag, related_name='tags') </code></pre> <p>And I want to get something like this from database:</p> <pre><code>[{'id': 1, 'tags': [1, 4, 8, 10]}, {'id': 6, 'tags': []}, {'id': 8, 'tags': [1, 2]}] </code></pre> <p>It is list of several SomeModel's dictionaries with SomeModel's id and ids of tags.</p> <p>What should the Django query looks like? I tried this:</p> <pre><code>&gt;&gt;&gt; SomeModel.objects.values('id', 'tags').filter(pk__in=[1,6,8]) [{'id': 1, 'tags': 1}, {'id': 1, 'tags': 4}, {'id': 1, 'tags': 8}, ...] </code></pre> <p>This is not what I want, so I tried something like this:</p> <pre><code>&gt;&gt;&gt; SomeModel.objects.values_list('id', 'tags').filter(pk__in=[1,6,8]) [(1, 1), (1, 4), (1, 8), ...] </code></pre> <p>And my last try was:</p> <pre><code>&gt;&gt;&gt; SomeModel.objects.values_list('id', 'tags', flat=True).filter(pk__in=[1,6,8]) ... TypeError: 'flat' is not valid when values_list is called with more than one field. </code></pre> <p>— </p> <p>Maybe Django cannot do this, so the most similar result to what I want is:</p> <pre><code>[{'id': 1, 'tags': 1}, {'id': 1, 'tags': 4}, {'id': 1, 'tags': 8}, ...] </code></pre> <p>Is there any Python build-in method which transform it to this?</p> <pre><code>[{'id': 1, 'tags': [1, 4, 8, 10]}, {'id': 6, 'tags': []}, {'id': 8, 'tags': [1, 2]}] </code></pre> <p><strong>— EDIT:</strong></p> <p>If I write method in <code>SomeModel</code>:</p> <pre><code>class SomeModel(models.Model): tags = models.ManyToManyField(Tag, related_name='tags') def get_tag_ids(self): aid = [] for a in self.answers.all(): aid.append(a.id) return aid </code></pre> <p>And then call:</p> <pre><code>&gt;&gt;&gt; sm = SomeModel.objects.only('id', 'tags').filter(pk__in=[1,6,8]) # Hit database &gt;&gt;&gt; for s in sm: ... s.get_tag_ids() ... &gt;&gt;&gt; # Hit database 3 times. </code></pre> <p>This is not working, because it access to database 4 times. I need just one access.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload