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
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}'
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})