Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(feat): add relate articles func #211

Merged
merged 3 commits into from
Dec 13, 2024
Merged

Conversation

losndu
Copy link
Collaborator

@losndu losndu commented Dec 13, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new field for selecting related articles in the article management interface, allowing up to three selections.
    • Added functionality to fetch and display related articles in article serializers.
    • Added a fieldset titled 'Related Content' in the article admin interface for better organization.
  • Bug Fixes

    • Enhanced validation to prevent selection of more than three related articles.
  • Documentation

    • Updated help text to guide users on selecting related articles.

Copy link

coderabbitai bot commented Dec 13, 2024

Walkthrough

The changes in this pull request involve the introduction of a related_articles field to the Article model, which allows for the selection of multiple related articles. The ArticleForm and ArticleAdmin classes are updated to accommodate this new field, including logic to filter the queryset and display related articles in the admin interface. Additionally, several serializers are modified to include the new field, ensuring proper handling during article creation and updates. Overall, these modifications enhance the management of related articles across the application.

Changes

File Path Change Summary
server/apps/research/admin/article_admin.py - Added related_articles fieldset in ArticleAdmin.
- Updated list_display to include display_authors.
- Minor formatting changes in save_model.
- New method current_slug_history.
server/apps/research/migrations/0015_article_related_articles.py - Introduced related_articles field as a ManyToManyField in Article model.
- Added help_text for user guidance.
server/apps/research/models/article.py - Added related_articles field as a ManyToManyField.
- Introduced get_related_articles method for fetching related articles.
- Updated clean method for validation.
server/apps/research/serializers/article_serializer.py - Added RelatedArticleSerializer.
- Updated ArticleListSerializer and ArticleSerializer to include related_articles.
- Modified ArticleCreateUpdateSerializer for related articles handling.

Possibly related PRs

Suggested reviewers

  • losndu

🐇 In the meadow, where stories intertwine,
Related articles dance, oh how they shine!
With fields and forms, we weave a tale,
Three at a time, we shall not fail.
A hop, a skip, through admin's embrace,
Together in knowledge, we find our place! 🌼📚


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (2)
server/apps/research/serializers/article_serializer.py (1)

Line range hint 123-124: Use exception chaining to preserve the original traceback

Similarly, in the update method, use exception chaining to maintain the traceback of the original exception.

Apply this change:

 except Exception as e:          
-    raise serializers.ValidationError(f"Error updating article: {str(e)}")
+    raise serializers.ValidationError(f"Error updating article: {str(e)}") from e
🧰 Tools
🪛 Ruff (0.8.2)

103-103: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


123-123: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

server/apps/research/admin/article_admin.py (1)

17-22: Remove redundant exclusion of status='draft'

In the queryset for related_articles, excluding articles with status='draft' is redundant since you've already filtered for status='ready'.

Consider simplifying the queryset:

 self.fields['related_articles'].queryset = Article.objects.filter(
     status='ready'
 ).exclude(
-    Q(pk=self.instance.pk) | Q(status='draft')
+    pk=self.instance.pk
 ).order_by('-scheduled_publish_time')
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 031fa6d and 80d6e67.

📒 Files selected for processing (4)
  • server/apps/research/admin/article_admin.py (4 hunks)
  • server/apps/research/migrations/0015_article_related_articles.py (1 hunks)
  • server/apps/research/models/article.py (4 hunks)
  • server/apps/research/serializers/article_serializer.py (3 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
server/apps/research/serializers/article_serializer.py

103-103: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


123-123: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

🔇 Additional comments (2)
server/apps/research/migrations/0015_article_related_articles.py (1)

1-18: Migration file looks good

The migration adds the related_articles field as expected, aligning with the model changes.

server/apps/research/models/article.py (1)

57-62: Verify the clean method enforces the related articles limit effectively

The clean method checks self.related_articles.count() to enforce a maximum of 3 related articles. Please verify that this validation works correctly during creation and updates, as self.related_articles may not include unsaved related articles during validation.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
server/apps/research/serializers/article_serializer.py (2)

6-16: LGTM! Consider enhancing the docstring.

The serializer implementation is well-structured. Consider adding more detail to the docstring about which fields are included and why they were chosen for the simplified view.

-    """Simplified serializer for related articles to prevent recursion"""
+    """Simplified serializer for related articles to prevent recursion.
+    
+    Includes essential fields (id, slug, title, authors, etc.) while excluding
+    detailed content to optimize response size and prevent circular references.
+    """

59-63: Consider additional filters for related articles queryset.

While filtering for status='ready' is good, consider excluding:

  1. The current article (to prevent self-reference)
  2. Articles that already have 3 related articles (to prevent exceeding the limit)
-        queryset=Article.objects.filter(status='ready'),
+        queryset=Article.objects.filter(status='ready').exclude(
+            id=serializers.CurrentValueDefault()
+        ),
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 80d6e67 and f8417af.

📒 Files selected for processing (1)
  • server/apps/research/serializers/article_serializer.py (3 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
server/apps/research/serializers/article_serializer.py

123-123: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

🔇 Additional comments (4)
server/apps/research/serializers/article_serializer.py (4)

40-44: LGTM! Consistent implementation of related articles.

The implementation aligns well with the ArticleListSerializer approach and properly includes the field in Meta.fields.

Also applies to: 52-52


73-76: LGTM! Clear validation logic.

The validation method effectively enforces the 3-article limit with a clear error message.


123-123: ⚠️ Potential issue

Add exception chaining in update method.

Similar to the create method, use exception chaining to preserve the original traceback.

-            raise serializers.ValidationError(f"Error updating article: {str(e)}")
+            raise serializers.ValidationError(f"Error updating article: {str(e)}") from e

Likely invalid or redundant comment.

🧰 Tools
🪛 Ruff (0.8.2)

123-123: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


21-25: Verify the existence of get_related_articles method.

The code calls obj.get_related_articles(), but we need to ensure this method exists in the Article model.

✅ Verification successful

✓ The get_related_articles method exists and is properly implemented

The get_related_articles method is implemented in the Article model with a smart fallback mechanism:

  • Returns up to 3 manually selected related articles if they exist
  • Falls back to articles with matching categories if no manual selections are made
  • Ensures only 'ready' status articles are returned in both cases
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for get_related_articles method in Article model
ast-grep --pattern 'class Article$$$:
  $$$
  def get_related_articles(self):
    $$$'

Length of output: 88


Script:

#!/bin/bash
# Let's try a broader search for Article class and related_articles
rg -A 5 "class Article" 

# Also search for any file containing get_related_articles
rg "get_related_articles"

# Search for Article model file specifically
fd "article.py|models.py" server/apps/research/

Length of output: 6706


Script:

#!/bin/bash
# Let's check the implementation of get_related_articles in the Article model
cat server/apps/research/models/article.py

Length of output: 6858

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
server/apps/research/serializers/article_serializer.py (1)

6-16: LGTM! Consider enhancing the docstring.

The serializer is well-structured and appropriately handles nested relationships while preventing recursion.

Consider using a more detailed docstring format:

-    """Simplified serializer for related articles to prevent recursion"""
+    """
+    Simplified serializer for related articles.
+    
+    Prevents recursion by excluding nested related_articles field while maintaining
+    essential relationship fields like authors and categories.
+    """
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f8417af and eb6c5a1.

📒 Files selected for processing (1)
  • server/apps/research/serializers/article_serializer.py (3 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
server/apps/research/serializers/article_serializer.py

103-103: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


123-123: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

🔇 Additional comments (3)
server/apps/research/serializers/article_serializer.py (3)

21-25: LGTM! Clean implementation of related articles in list view.

The implementation correctly uses SerializerMethodField and properly handles nested serialization with context passing.


40-44: LGTM! Consistent implementation of related articles in detail view.

The implementation maintains consistency with the list serializer and properly includes the field in Meta configuration.

Also applies to: 52-52


59-76: LGTM! Well-implemented related articles field with proper validation.

The implementation correctly:

  • Filters the queryset to only include ready articles
  • Validates the maximum limit of 3 related articles
  • Makes the field optional

@losndu losndu merged commit c5feea0 into main Dec 13, 2024
3 checks passed
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.

1 participant