Skip to content

Instantly share code, notes, and snippets.

@bmispelon
Created June 25, 2024 13:22
Show Gist options
  • Save bmispelon/646232890a1da3f3d0ed773511e39aad to your computer and use it in GitHub Desktop.
Save bmispelon/646232890a1da3f3d0ed773511e39aad to your computer and use it in GitHub Desktop.
Attempt at replicating https://softwarecrafts.co.uk/100-words/day-119 with plain prefetches
<table>
{% for client in clients %}
...
<tr>
...
<td>
<select>
{% for group in client.groups.all %}{# prefetched #}
<option{% if group.pk in user_groups %} selected{% endif %}>{{group}}</option>
{% endfor %}
</select>
</td>
</tr>
...
{% endfor %}
</table>
# reversed-engineered from your example
from django.db import models
class Client(models.Model):
pass
class Group(models.Model):
client = models.ForeignKey("Client", on_delete=models.CASCADE, related_name="groups")
class User(models.Model):
client = models.ForeignKey("Client", on_delete=models.CASCADE, related_name="users")
groups = models.ManyToManyField("Group")
from django.shortcuts import render
from .models import Client
def client_list(request):
return render(
request,
"client_list.html",
{
"clients": Client.objects.prefetch_related("groups"),
"user_groups": set(request.user.groups.values_list("pk", flat=True)),
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment