Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid duplicates bcs of __str__ function Django

I have model with Foreign Key and i use name of that foreinKey in my template and i have 38 sql queries bcs of __str__ funciton in my model

How can i show name of foreignKey without duplicates and similiar queries?

models.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class SectionList(models.Model):
    GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True)
    object = models.ForeignKey(ObjectList, related_name='object', on_delete=models.CASCADE, default=None,
                               verbose_name='Объект')
    clean_sections = models.ForeignKey(CleanSections, on_delete=models.CASCADE, null=True)

    class Meta:
        verbose_name = 'Раздел'
        verbose_name_plural = 'Разделы'

    def __str__(self):
        return f'{self.clean_sections.name}'

enter image description here

enter image description here

>Solution :

You can add select_related('clean_sections') to SectionList queryset in view

# views.py

def your_view(request):
    section_lists = SectionList.objects.select_related('clean_sections').all()
    ...
    return render(request, 'your_template.html', {'section_lists': section_lists})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading