S
S
Semyon Pyatnitsky2017-05-03 20:33:07
Django
Semyon Pyatnitsky, 2017-05-03 20:33:07

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

I'm trying to display all clients and their contacts (individuals)
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>

But only displays clients. in Yii2 and Laravel, it was solved by specifying the connection in the with() method. in rails, this is includes(). Help))
Yii2 builds correctly through with 2 requests and conclusions on the screenshots. the numbers after the name are the ids of the contacts that are associated with the counterparty in the workplace table.8cc368ec8f734f94b2411aab12613d46.png
91daf87b76784d109886f8f0af396622.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sim3x, 2017-05-03
@sim3x

{% for contact in client.contacts.all %}

N
Neoliz, 2017-05-29
@timofeydeys

def post_list(request):
    clients = Client.objects.prefetch_related('contacts').all()
    return render(request, 'blog/post_list.html', {'clients': clients})

It should be so))
def post_list(request):
    clients = Client.objects.all().prefetch_related('contacts')
    return render(request, 'blog/post_list.html', {'clients': clients})

And if you want to make a nested query, according to a specific queryset, then like this:
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 question

Ask a Question

731 491 924 answers to any question