Skip to content

feat: Single table for uploaded images - #10069

Closed
Reza98Sh wants to merge 33 commits into
inventree:masterfrom
Reza98Sh:feature/issue9788
Closed

Reza98Sh wants to merge 33 commits into
inventree:masterfrom
Reza98Sh:feature/issue9788

Conversation

@Reza98Sh

@Reza98Sh Reza98Sh commented Jul 24, 2025 •

Copy link
Copy Markdown
Contributor

Refactoring how "Images" are stored, moving to a single table approach.

Tasks

  • Create new table for uploaded images
  • Add data migration for migrate old images into new upload image table
  • Remove old tables
  • Add a mixin class for models which will have image associated with them
  • Expose new model to API
  • Mixin class must provide method for accessing image
  • Add previous Image functionalities to new image model
  • Add images carousel for multiple part pictures
  • Update Image UI for parts and company
  • Update unit tests
  • Test for migrations
  • Update create test DB script

A new API namespace for images is introduced:

Method Endpoint Description
GET /api/image/ List all images
POST /api/image/ Upload a new image
GET /api/image/<pk>/ Retrieve details for a specific image
PATCH /api/image/<pk>/ Update a specific image
DELETE /api/image/<pk>/ Delete a specific image
GET /api/image/thumbs/ Retrieve image thumbnails

Demo

Screencast.from.2025-07-24.16-00-28.webm

Next Steps & Request for Feedback

This PR covers the core implementation of the new image storage architecture. The main logic, database changes, and UI updates are in place.

Before I proceed with updating the unit tests and update test database data, I would like to request a review of the current approach.

Could you please review the architecture and implementation to confirm if this is the desired direction?

Once the approach is approved, I will finalize the PR by completing the remaining tasks and ensuring full test coverage.

Thank you

Related Issues

Closes #9788

Reza98Sh added 11 commits June 30, 2025 18:30
- Update .gitignore to exclude media and backup directories
- Implement UploadImageList and UploadImageDetail API views
- Enhance UploadedImage model with primary image validation
- Update serializers to include model_type and model_id fields
- Modify DetailsImage component for image upload functionality
- Integrate DetailsImageCarousel for displaying multiple images
- Update PartDetail page to utilize new image handling features
- Refactor ColumnRenderers to display primary image thumbnailsAdd image handling to Part model and create migration for UploadedImage
- Updated InvenTreeImageUploadMixin to delete images before the object deletion.
- Modified UploadImageAdmin to display image in the admin list.
- Added UploadImageThumbs API endpoint to retrieve thumbnails with usage count.
- Introduced helper function to manage part image directory.
- Created migration to transfer company images to Add UploadedImage model and API endpoints for image uploads
- Update .gitignore to exclude media and backup directories
- Implement UploadImageList and UploadImageDetail API views
- Enhance UploadedImage model with primary image validation
- Update serializers to include model_type and model_id fields
- Modify DetailsImage component for image upload functionality
- Integrate DetailsImageCarousel for displaying multiple images
- Update PartDetail page to utilize new image handling features
- Refactor ColumnRenderers to display primary image thumbnailsAdd image handling to Part model and create migration for UploadedImage
- Modified DetailsImage.tsx to include model_id and model_type in the download image form, ensuring proper handling of image uploads.
- Adjusted the delete image functionality to set a backup image after deletion.
@netlify

netlify Bot commented Jul 24, 2025 •

Copy link
Copy Markdown

✅ Deploy Preview for inventree-web-pui-preview ready!

Name Link
🔨 Latest commit c1f0e3d
🔍 Latest deploy log https://app.netlify.com/projects/inventree-web-pui-preview/deploys/689b84ceb0a35d000807641a
😎 Deploy Preview https://deploy-preview-10069--inventree-web-pui-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
Lighthouse
Lighthouse
1 paths audited
Performance: 97 (no change from production)
Accessibility: 81 (no change from production)
Best Practices: 100 (no change from production)
SEO: 78 (no change from production)
PWA: -
View the detailed breakdown and full score reports

To edit notification comments on pull requests, go to your Netlify project configuration.

@Reza98Sh Reza98Sh changed the title Feature/issue9788 Single table for file images #9788 Jul 24, 2025
@Reza98Sh Reza98Sh changed the title Single table for file images #9788 Single table for file images Jul 24, 2025
@Reza98Sh Reza98Sh changed the title Single table for file images Single table for upload images Jul 24, 2025
@matmair matmair added enhancement This is an suggested enhancement or new feature part Related to Part models api Relates to the API User Interface Related to the frontend / User Interface labels Jul 24, 2025
@matmair matmair added this to the 1.0.0 milestone Jul 24, 2025
@matmair matmair changed the title Single table for upload images feat: Single table for uploaded images Jul 24, 2025

@matmair matmair left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is a good start; a few comments:

  • I think UploadedImage is a misleading name; all images are uploaded in some form so it should be just Image (maybe InvenTreeImage)
  • I think it would be better to use generic-relations instead of building your own choice and validation mechanisms as that enables easier use within plugins
  • the removal of thumbnail in the apis makes no sense to me - why not link the thumbnail of the primary image and break less stuff?
  • In a few places code is commented out instbeing beeing removed; not a fan of that, please clean that up
  • os.path can have issues when switching between operating system, please use pathlib.Path - here is a conversion table https://docs.python.org/3/library/pathlib.html#corresponding-tools

Things to polish this a bit more:

  • add a bit of docs for how images work
  • add a control to the Admin Center to view and possibly remove images instead of the old django admin page
  • add unit test (you already have that listed)
  • update the description of your PR to describe how this change the api for users

Comment on lines +16 to +18
for part in Part.objects.all():
if not part.image:
continue

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please just filter for parts that have images

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thanks! Got it. Will update soon.

part.image.close()

# Extract the base filename to avoid path issues
filename = os.path.basename(part.image.name)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please use pathlib

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thanks! Got it. Will update soon.

Comment on lines +14 to +16
for company in Company.objects.all():
if not company.image:
continue

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please use a filter on the object instead

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thanks! Got it. Will update soon.

company.image.close()

# Extract the base filename to avoid path issues
filename = os.path.basename(company.image.name)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please use pathlib

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thanks! Got it. Will update soon.

Comment thread src/backend/InvenTree/common/admin.py Outdated
Comment on lines +39 to +55
@admin.register(common.models.UploadedImage)
class UploadImageAdmin(admin.ModelAdmin):
"""Admin interface for UploadedImage objects."""

def formfield_for_dbfield(self, db_field, request, **kwargs):
"""Provide custom choices for 'model_type' field."""
if db_field.name == 'model_type':
db_field.choices = common.validators.get_model_options(
InvenTree.models.InvenTreeImageUploadMixin
)

return super().formfield_for_dbfield(db_field, request, **kwargs)

list_display = ('model_type', 'model_id', 'image', 'primary')

search_fields = ('image',)
list_filter = ('model_type',)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We do not promote usage of the django admin anymore, please remove this

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think "not promoting" means "not support" here - for ~20 LOC we get a low-level admin interface for free which does come in handy sometimes?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thanks! Got it. Will update soon.

type: ModelType.purchaseorder
})}
image={supplier.thumbnail || supplier.image}
image={supplier?.image.thumbnail || supplier?.image.image}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Does this mean there is no placeholder image anymore?

Comment on lines -633 to -760
{enableRevisionSelection && (
<Stack gap='xs'>
<Text>{t`Select Part Revision`}</Text>
<RevisionSelector part={part} options={partRevisionOptions} />
</Stack>
)}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why is this removed?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You’re right, this was removed by mistake during a local merge. I’ll restore it immediately. Sorry about that.

Comment on lines +587 to +586
subtitle={subtitle}
imageUrl={order.customer_detail?.image}
subtitle={order.description}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why is this changed?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You’re right, this was changed by mistake during a local merge. I’ll restore it immediately. Sorry about that.

})
.catch((error) => {
// Handle error
console.error('Error setting new image:', error);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please remove this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thanks! Got it. Will update soon.

Comment on lines +37 to +43
const get_image_src = () => {
// Get primary image source
const primary_image = part?.images?.find(
(img: any) => img.primary === true
);
return primary_image?.thumbnail ?? primary_image?.image;
};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Question: Did you look into performance with many images?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I see two options to optimize this:

  1. Add the primary image URL directly from the backend serializer.
  2. Use useMemo on the frontend to avoid re-computation.

I believe option 1 is the superior approach as it’s more performant and keeps the frontend logic cleaner.

useMemo would be more of a patch. Do you agree? I’ll proceed with the backend change.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We use useMemo a lot, it is the right approach if you only can / want to touch the frontend.
As pointed out in the backend comments, I think the old (primary) image and thumbnail fields should be preserved so this would not be needed.

@matmair

matmair commented Jul 24, 2025

Copy link
Copy Markdown
Member

Also: This needs a new api revision - see https://docs.inventree.org/en/stable/develop/contributing/#api-versioning - and CI won't run till the conflicts are resolved

"""Custom delete method for InvenTreeImageUploadMixin.

- Before deleting the object, check if there are any uploaded images associated with it.
- If so, delete the images first

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can an image be uploaded against multiple objects simultaneously? Or is it a single image-to-object association?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The implementation allows for a many-to-many association, meaning an image can indeed be linked to multiple objects simultaneously via the “select existing image” feature.
It doesn't save duplicate images.

Comment thread src/backend/InvenTree/common/admin.py Outdated
Comment on lines +39 to +55
@admin.register(common.models.UploadedImage)
class UploadImageAdmin(admin.ModelAdmin):
"""Admin interface for UploadedImage objects."""

def formfield_for_dbfield(self, db_field, request, **kwargs):
"""Provide custom choices for 'model_type' field."""
if db_field.name == 'model_type':
db_field.choices = common.validators.get_model_options(
InvenTree.models.InvenTreeImageUploadMixin
)

return super().formfield_for_dbfield(db_field, request, **kwargs)

list_display = ('model_type', 'model_id', 'image', 'primary')

search_fields = ('image',)
list_filter = ('model_type',)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think "not promoting" means "not support" here - for ~20 LOC we get a low-level admin interface for free which does come in handy sometimes?

Comment thread src/backend/InvenTree/common/models.py Outdated

@cleanup.ignore
class UploadedImage(models.Model):
"""Class which represents an uploaded image for Part and Company.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

e.g.

"""Class which represents an uploaded image linked to another model instance."""

next_img = (
UploadedImage.objects.filter(
model_type=self.model_type, model_id=self.model_id
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

You probably also want to exclude the current ID from this filter - inside an atomic transaction, can we guarantee that the "self" ID hasn't been removed yet?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch. You’re right, I should exclude self.pk from the query to prevent a potential race condition. I’ll fix that. Thanks!

image = InvenTree.serializers.InvenTreeImageSerializerField(
required=False, allow_null=True
)
thumbnail = serializers.CharField(source='get_thumbnail_url', read_only=True)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This may cause issues because it is calling a function on each item in the dataset - we will need to carefully test that it does not execute a high number of database queries when performing a LIST API operation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

You’re right to point out the risk of an N+1 query problem on list views.

I will investigate this.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Happy to provide some pointers or assistance in this area, it's a very nuanced concept

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks a lot, I really appreciate the offer! I’ll take an initial look myself, and will definitely ping you if I have any questions or could use some pointers. My initial thought was to use a tool like django-silk to profile the queries and check for optimization opportunities.

@matmair matmair Jul 27, 2025 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Our dev setup already shops with a variety of tools and should alert you once you add a large enough test-dataset; they run during backend tests

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I’m encountering a test failure in part.test_api.PartDetailTests.test_part_operations related to an excessive number of database queries.

The failure occurs during the PATCH request to rename a part:

response = self.patch(url, {'name': 'a new better name'})

The test expects the operation to complete in fewer than 250 queries, but the test runner reports 346 queries, causing an AssertionError.

Here’s the interesting part: to investigate this, I manually performed the same part rename operation on a development server with django-silk enabled for profiling. Silk reported only 92 queries for the entire request.

This is a significant discrepancy, and it suggests the issue might be specific to the test environment’s query counting mechanism rather than the core logic of the rename operation itself.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The test environment is staged with a reasonable amount of data to find o+1 issues. You will need to run silk with the test running to reproduce this; certainly sounds like something is iterating over parts.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I found the problem it related to django-silk. :)
In test environment it count silk query also that cause excessive number of database queries


def forwards(apps, schema_editor):
Company = apps.get_model('company', 'Company')
UploadedImage = apps.get_model('common', 'UploadedImage')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This migration must be in the "company" app, and it must be before the new 0076_remove_company_image migration file. Otherwise, the images may be deleted before this migration runs!

Alternatively, add this migration as a requirement for the 0076 migration in "company" app.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thanks! Got it. Will update soon.

@Reza98Sh

Reza98Sh commented Aug 6, 2025

Copy link
Copy Markdown
Contributor Author

@SchrodingersGat

Excuse me, I have a trouble with images fields in PartBriefSerializer,
This serializer has been used in other serializers in several place.

My question is: What is the best practice in this scenario to resolve the N+1 issue? Should I go through every view/serializer that uses PartBriefSerializer and modify its queryset to use

…nd update related methods; adjust image upload path in migration and handle remote image processing with error handling in serializer
@Reza98Sh

Reza98Sh commented Aug 6, 2025

Copy link
Copy Markdown
Contributor Author

@matmair, @SchrodingersGat,

I’m looking into updating our tests for the image management API. I see two possible approaches, and I’d like to get your opinion on which is better.

Option 1: We could update the existing image-related tests within the Part application to be more comprehensive.

Option 2: We could create a new, centralized test file at common/test_api.py and move all image-related tests there, making them more generic.

What do you think is the best path forward?

@matmair

matmair commented Aug 6, 2025

Copy link
Copy Markdown
Member

If the refactored PR is generic, it should have tests in common/; if there is still image-related code in part/ those parts should be covered by tests in the part/ directory.

this will be easier to judge when there are no conflicts anymore and the CI is able to run through. You will be provided with a visual coverage breakdown and a clear list what parts of code still require coverage here in the PR by a bot

…est cases; enhance image generation and validation in API
…; streamline image handling and retrieval in serializers and frontend components
…e 'image' with 'thumbnail_url' and 'image_url' for consistency and improved retrieval
…deprecated methods, optimize image retrieval, and update related references for consistency
…s and API endpoints for new image architecture, and enhance related tests
@Reza98Sh

Copy link
Copy Markdown
Contributor Author

@SchrodingersGat @matmair

Thank you for the feedback!
I learned a lot from your comments and have refactored based on them.

Here’s a summary of the changes:

  • Replaced all os path operations with pathlib
  • Refactored migrate_company_images.py and migrate_part_images.py for better efficiency. During this refactoring, I discovered that Part images were stored in duplicate. To resolve this, I implemented a sha256–based mechanism to prevent duplicate image storage.Later, I thought we could adopt this mechanism more broadly instead of the current existing_image check — by storing the image hash and comparing it when uploading new images to avoid duplicates.
  • Improved function docstrings for better API documentation generation.
  • Implemented a custom field CustomStdImage(StdImageField) to automatically delete unused images.
  • Renamed the UploadedImage class to InvenTreeImage, and using GenericForeignKey for more flexible model relations.
  • Added image_url and thumbnail_url fields, along with an InvenTreeImageSerializerMixin to make image serialization more reusable.
  • Reworked the part duplication mechanism to properly handle new images.
  • Restored code that was unintentionally removed during a previous merge.
  • Reviewed all new and modified API endpoints for potential N+1 query issues and optimized them where needed.
  • Added dedicated API tests for InvenTreeImage.
  • Created TestLegacyImageMigration to test old image migration functionality.
  • Addressed several other minor issues mentioned in the feedback.

@Reza98Sh
Reza98Sh marked this pull request as ready for review August 11, 2025 17:28
@matmair

matmair commented Aug 11, 2025 •

Copy link
Copy Markdown
Member

@Reza98Sh can you please address the merge conflicts before we starts another review round?
You can do this by pulling from the master branch

@Reza98Sh

Copy link
Copy Markdown
Contributor Author

Sure, I’ll address the merge conflicts and pull from master as soon as possible.

…rt model

- Incremented API version to 385 with new features and changes documented.
- Removed 'image' field from Part model in migration 0143.
- Cleaned up test cases related to image handling.
@Reza98Sh

Copy link
Copy Markdown
Contributor Author

Conflicts resolved and branch updated.

@matmair

matmair commented Aug 12, 2025

Copy link
Copy Markdown
Member

Thank you; if will wait for the CI and then run some on-prem tests

@Reza98Sh

Copy link
Copy Markdown
Contributor Author

It seems some tests have failed. My plan was to review and update all other the tests in the next PR, after the proposed implementation for images is approved.

@Reza98Sh

Copy link
Copy Markdown
Contributor Author

@matmair @SchrodingersGat

Excuse me, I am preparing for Hacktoberfest and I have several PRs planned for October (including this one).

I would like to close this PR for now, fix all test failures, and then open a clean PR in October, so it will count for Hacktoberfest together with my other planned PRs.

Would that be okay for you?

@matmair

matmair commented Sep 18, 2025

Copy link
Copy Markdown
Member

Sure, go ahead

@Reza98Sh Reza98Sh closed this Sep 18, 2025
@Reza98Sh
Reza98Sh deleted the feature/issue9788 branch September 27, 2025 17:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Relates to the API enhancement This is an suggested enhancement or new feature part Related to Part models User Interface Related to the frontend / User Interface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FR] Multiple Part Pictures

3 participants