Skip to content

Fix AttributeError: 'Issue' object has no attribute 'code_sections'#1369

Merged
robertatakenaka merged 5 commits intomainfrom
copilot/fix-attribute-error-issue
Mar 4, 2026
Merged

Fix AttributeError: 'Issue' object has no attribute 'code_sections'#1369
robertatakenaka merged 5 commits intomainfrom
copilot/fix-attribute-error-issue

Conversation

Copy link
Contributor

Copilot AI commented Mar 4, 2026

code_sections foi removido do model Issue na migration 0020 e substituído por table_of_contents, mas articlemeta_format.py ainda referenciava o atributo antigo, quebrando a exportação de artigos para o AM.

O que esse PR faz?

  • Substitui self.obj.code_sections.all() por self.obj.table_of_contents.select_related("journal_toc__language").all() em _format_code_sections, eliminando o padrão de N+1 queries ao iterar as linhas do TOC
  • Atualiza os acessos de atributos para a nova estrutura TableOfContents → JournalTableOfContents:
    • section.code_section.codetoc.journal_toc.code
    • section.language.code2toc.journal_toc.language.code2
    • section.texttoc.journal_toc.text
  • Corrige bug pré-existente: data.append(item) estava fora do bloco if code:, causando NameError quando code é None
  • Adiciona testes unitários em issue/test_format_code_sections.py cobrindo os cenários do método _format_code_sections

Onde a revisão poderia começar?

issue/formats/articlemeta_format.py → método _format_code_sections

issue/test_format_code_sections.py → testes unitários do método

Como este poderia ser testado manualmente?

Disparar a exportação de um artigo para o ArticleMeta (articlemeta_format) e verificar que o processo conclui sem AttributeError. Confirmar que o campo v49 do fascículo é populado corretamente quando há seções associadas via table_of_contents.

Para executar os testes automatizados:

pytest issue/test_format_code_sections.py

Algum cenário de contexto que queira dar?

A migration 0020 removeu code_sections e sections do Issue, consolidando ambos em table_of_contents (FK para JournalTableOfContents). O formatter de ArticleMeta não foi atualizado junto, deixando a exportação quebrada.

O uso de select_related("journal_toc__language") garante que journal_toc e seu language sejam carregados em uma única query, evitando consultas extras por linha durante a exportação.

Os testes unitários utilizam SimpleTestCase e MagicMock para evitar dependência de banco de dados, verificando: entradas v49 corretas com código/idioma/texto; omissão das chaves l e t quando ausentes; ausência de v49 quando não há seções ou nenhuma seção possui código; que select_related("journal_toc__language") é chamado corretamente; e que o atributo removido code_sections.all nunca é acionado.

Screenshots

N/A

Quais são tickets relevantes?

#1368

Referências

Original prompt

This section details on the original issue you should resolve

<issue_title>AttributeError: 'Issue' object has no attribute 'code_sections'</issue_title>
<issue_description>### Descrição do problema
Erro obtido ao executar a exportação de artigo para AM.
Note que code_sections estava excedente, há outro atributo que faz o mesmo papel. Encontrar outras ocorrêcias de code_sections e trocar pelo atributo correto.

{"errors": null, "events": ["building articlemeta format for article", "check articlemeta exportation demand", "building articlemeta format for issue"], "response": "{'collection': 'dom', 'article': {'v30': [{'_': 'Rev. Segur. Cienc. Def.'}], 'v62': [{'_': 'Universidad Nacional para la Defensa General Juan Pablo Duarte y Díez'}], 'v100': [{'_': 'Revista Seguridad Ciencia & Defensa '}], 'v435': [{'t': 'epub', '_': '2636-2309'}, {'t': 'ppub', '_': '2413-869X'}], 'v10': [{'k': '0009-0000-1334-2833', 'n': 'Boris', '1': 'aff1', 's': 'Saavedra', 'r': 'ND', '_': ''}, {'k': '0009-0002-4356-3260', 'n': 'Chase Logan', '1': 'aff2', 's': 'Boone', 'r': 'ND', '_': ''}], 'v70': [{'i': 'aff1', 'l': '1', '4': 'Universidad de Los Andes', 'p': 'Venezuela', 'e': 'saavedrab@ndu.edu', '_': 'National Defense University', '9': '1 National Defense University, Venezuela, saavedrab@ndu.edu Universidad de Los Andes National Defense University Venezuela saavedrab@ndu.edu'}, {'i': 'aff2', 'l': '2', '4': 'National Defense University', 'p': 'USA', 'e': 'chase.l.boone.civ@ndu.edu', '_': 'National Defense University', '9': '2 National Defense University, Estados Unidos, chase.l.boone.civ@ndu.edu National Defense University National Defense University USA chase.l.boone.civ@ndu.edu'}], 'v240': [{'i': 'aff1', 'p': 'VE', '_': 'National Defense University'}, {'i': 'aff2', 'p': 'US', '_': 'National Defense University'}], 'v170': [{'_': '1 National Defense University, Venezuela, saavedrab@ndu.edu Universidad de Los Andes National Defense University Venezuela saavedrab@ndu.edu'}, {'_': '2 National Defense University, Estados Unidos, chase.l.boone.civ@ndu.edu National Defense University National Defense University USA chase.l.boone.civ@ndu.edu'}], 'v72': [{'_': '40'}], 'v40': [{'_': 'es'}], 'v120': [{'_': 'XML_1.1'}], 'v71': [{'_': 'oa'}], 'v337': [{'d': '10.59794/rscd.2025.v11i11.149', 'l': 'es', '_': ''}], 'v83': [{'a': 'Resumen La guerra moderna abarca tanto el ámbito físico como el cibernético. Las fuerzas armadas actuales enfrentan amenazas en múltiples dominios, tales como: tierra, mar, aire, espacio y el ciberespacio. Por ello, integrar las operaciones cibernéticas con las operaciones en los dominios físicos se ha vuelto esencial para lograr ventajas en el campo de batalla. La doctrina estadounidense de Operaciones Multidominio (OMD) plantea contrarrestar amenazas simultáneas en todos los dominios de la guerra mediante la convergencia de efectos y fuerzas. Sin embargo, muchos países aliados aún enfrentan desafíos para incorporar plenamente las capacidades cibernéticas a sus operaciones convencionales. Este artículo analiza la importancia de integrar el dominio cibernético con los dominios físicos en las operaciones de seguridad y defensa, apoyándose en la doctrina de Operaciones Multidominio (OMD) de EE. UU., estudios de caso regionales y tendencias hemisféricas, con el fin de orientar a los países de América Latina y el Caribe en la construcción de capacidades multimisión frente a amenazas híbridas.', 'l': 'es', '_': ''}, {'a': \"Abstract Modern warfare encompasses both the physical and cybernetic realms. Today's armed forces face threats in multiple domains, such as land, sea, air, space, and cyberspace. As such, integrating cyber operations with operations in the physical domains has become essential to achieving advantages on the battlefield. The U.S. doctrine of Multi-Domain Operations (MDO) proposes countering simultaneous threats in all domains of warfare through the convergence of effects and forces. However, many allied countries still face challenges in fully incorporating cyber capabilities into their conventional operations. This article analyzes the importance of integrating the cyber domain with the physical domains in security and defense operations, based on the U.S. Multi-Domain Operations (MDO) doctrine, regional case studies, and hemispheric trends, in order to guide Latin American and Caribbean countries in building multi-mission capabilities against hybrid threats.\", 'l': 'en', '_': ''}], 'v85': [{'k': 'Dominio', 'l': 'es', '_': ''}, {'k': 'operaciones multidominio (OMD)', 'l': 'es', '_': ''}, {'k': 'guerra cibernética', 'l': 'es', '_': ''}, {'k': 'sistemas ciberfísicos (SCF)', 'l': 'es', '_': ''}, {'k': 'inteligencia artificial generativa (IAG)', 'l': 'es', '_': ''}, {'k': 'Domain', 'l': 'en', '_': ''}, {'k': 'Multi-Domain Operations (OMD)', 'l': 'en', '_': ''}, {'k': 'Cyber Warfare', 'l': 'en', '_': ''}, {'k': 'Cyber-Physical Systems (SCF)', 'l': 'en', '_': ''}, {'k': 'Generative Artificial Int...

</details>



<!-- START COPILOT CODING AGENT SUFFIX -->

- Fixes scieloorg/core#1368

<!-- START COPILOT CODING AGENT TIPS -->
---

💬 We'd love your input! Share your thoughts on Copilot coding agent in our [2 minute survey](https://gh.io/copilot-coding-agent-survey).

Co-authored-by: robertatakenaka <505143+robertatakenaka@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix AttributeError related to code_sections attribute Fix AttributeError: 'Issue' object has no attribute 'code_sections' Mar 4, 2026
@robertatakenaka
Copy link
Member

@copilot crie testes automatizados

Co-authored-by: robertatakenaka <505143+robertatakenaka@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Mar 4, 2026

@copilot crie testes automatizados

Added unit tests in issue/test_format_code_sections.py (commit 8947009). Uses SimpleTestCase + MagicMock to avoid database dependency and covers:

  • Sections with code/language/text produce correct v49 entries
  • Sections without code are skipped (no v49 entry)
  • Missing language omits the l key
  • Missing text omits the t key
  • Empty table_of_contents does not set v49
  • table_of_contents.all() is called instead of code_sections

@robertatakenaka robertatakenaka marked this pull request as ready for review March 4, 2026 01:23
Copilot AI review requested due to automatic review settings March 4, 2026 01:23
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Atualiza a exportação do Issue para ArticleMeta corrigindo a referência ao atributo removido Issue.code_sections, alinhando o formatter ao novo relacionamento Issue.table_of_contents → TableOfContents.journal_toc, e adiciona testes unitários para _format_code_sections.

Changes:

  • Troca o acesso de code_sections para table_of_contents em _format_code_sections, navegando via toc.journal_toc.
  • Ajusta os campos exportados (code/language/text) para a nova estrutura e corrige bug que podia gerar NameError quando code era None.
  • Adiciona testes unitários com mocks cobrindo os cenários principais de formatação/omissão de chaves.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
issue/formats/articlemeta_format.py Corrige o formatter para ler seções via table_of_contents e evita erro ao montar v49.
issue/test_format_code_sections.py Inclui testes unitários para _format_code_sections com cenários de presença/ausência de code/idioma/texto.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +356 to +360
for toc in self.obj.table_of_contents.all():
journal_toc = toc.journal_toc
code = getattr(journal_toc, "code", None)
lang = getattr(journal_toc.language, "code2", None) if journal_toc.language else None
text = journal_toc.text
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self.obj.table_of_contents.all() returns TOC rows, but each toc.journal_toc (and then journal_toc.language) can trigger extra DB queries per row. Consider using self.obj.table_of_contents.select_related("journal_toc__language").all() (or equivalent prefetching upstream) to avoid an N+1 query pattern during exports.

Copilot uses AI. Check for mistakes.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot apply changes based on this feedback

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied in commit 1223bed. Changed self.obj.table_of_contents.all() to self.obj.table_of_contents.select_related("journal_toc__language").all() to fetch journal_toc and its language in a single query. Updated the test mock and assertions to match the chained call.

robertatakenaka and others added 2 commits March 3, 2026 22:29
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: robertatakenaka <505143+robertatakenaka@users.noreply.github.com>
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +356 to +360
for toc in self.obj.table_of_contents.select_related("journal_toc__language").all():
journal_toc = toc.journal_toc
code = getattr(journal_toc, "code", None)
lang = getattr(journal_toc.language, "code2", None) if journal_toc.language else None
text = journal_toc.text
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JournalTableOfContents is collection-specific, but _format_code_sections currently iterates over all issue.table_of_contents rows without filtering by the formatter’s collection_acron (or self.scielo_journal.collection). If an Issue has TOC entries loaded for multiple collections (possible via multiple AMIssue imports), the export can mix sections from different collections into v49. Filter the queryset by the active collection before formatting, and add/adjust a unit test to cover the multi-collection case.

Copilot uses AI. Check for mistakes.
@robertatakenaka robertatakenaka merged commit 44edee3 into main Mar 4, 2026
7 checks passed
robertatakenaka added a commit to robertatakenaka/core that referenced this pull request Mar 11, 2026
…cieloorg#1369)

* Initial plan

* Fix AttributeError: 'Issue' object has no attribute 'code_sections'

Co-authored-by: robertatakenaka <505143+robertatakenaka@users.noreply.github.com>

* Add unit tests for _format_code_sections using table_of_contents

Co-authored-by: robertatakenaka <505143+robertatakenaka@users.noreply.github.com>

* Update issue/test_format_code_sections.py

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Use select_related to avoid N+1 queries in _format_code_sections

Co-authored-by: robertatakenaka <505143+robertatakenaka@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: robertatakenaka <505143+robertatakenaka@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants