Answer the question
In order to leave comments, you need to log in
prefetch_related not working in django?
There are 3 models
from django.db import models
from django.utils import timezone
class Contact(models.Model):
IDContact = models.IntegerField(primary_key=True)
NameContact = models.CharField(max_length=255)
FamilyContact = models.CharField(max_length=255)
SoNameContact = models.CharField(max_length=255)
class Meta:
db_table = 'contacts'
class Client(models.Model):
ClientId = models.IntegerField(primary_key=True)
ClientName = models.CharField(max_length=255)
contacts = models.ManyToManyField('Contact', through='Workplace')
class Meta:
db_table = 'clients'
class Workplace(models.Model):
client = models.ForeignKey('Client', db_column='wpClientId')
contact = models.ForeignKey('Contact', db_column='wpContactId')
class Meta:
db_table = 'Workplace'
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.User')
category = models.ForeignKey('PostCategory')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class PostCategory(models.Model):
name = models.CharField(max_length=200)
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def __str__(self):
return self.name
def post_list(request):
clients = Client.objects.prefetch_related('contacts').all()
return render(request, 'blog/post_list.html', {'clients': clients})
<html>
<body>
{% for client in clients %}
<div>
<p><a href="">{{ client.ClientName }}</a></p>
{% for contact in client.contacts.all %}
{{ contact.NameContact }}
{% endfor %}
</div>
{% endfor %}
</body>
</html>
Answer the question
In order to leave comments, you need to log in
def post_list(request):
clients = Client.objects.prefetch_related('contacts').all()
return render(request, 'blog/post_list.html', {'clients': clients})
def post_list(request):
clients = Client.objects.all().prefetch_related('contacts')
return render(request, 'blog/post_list.html', {'clients': clients})
from django.db.models import Prefetch
def post_list(request):
clients = Client.objects.all().prefetch_related(Prefetch('contacts', queryset=Contanct.objects.all())) # В Queryset скармливаешь просто queryset и делается вложенный запрос.
return render(request, 'blog/post_list.html', {'clients': clients})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question