winipedia-utils 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. winipedia_utils/__init__.py +1 -0
  2. winipedia_utils/concurrent/__init__.py +1 -0
  3. winipedia_utils/concurrent/concurrent.py +242 -0
  4. winipedia_utils/concurrent/multiprocessing.py +115 -0
  5. winipedia_utils/concurrent/multithreading.py +93 -0
  6. winipedia_utils/consts.py +22 -0
  7. winipedia_utils/data/__init__.py +1 -0
  8. winipedia_utils/data/dataframe.py +7 -0
  9. winipedia_utils/django/__init__.py +27 -0
  10. winipedia_utils/django/bulk.py +536 -0
  11. winipedia_utils/django/command.py +334 -0
  12. winipedia_utils/django/database.py +304 -0
  13. winipedia_utils/git/__init__.py +1 -0
  14. winipedia_utils/git/gitignore.py +80 -0
  15. winipedia_utils/git/pre_commit/__init__.py +1 -0
  16. winipedia_utils/git/pre_commit/config.py +60 -0
  17. winipedia_utils/git/pre_commit/hooks.py +109 -0
  18. winipedia_utils/git/pre_commit/run_hooks.py +49 -0
  19. winipedia_utils/iterating/__init__.py +1 -0
  20. winipedia_utils/iterating/iterate.py +29 -0
  21. winipedia_utils/logging/__init__.py +1 -0
  22. winipedia_utils/logging/ansi.py +6 -0
  23. winipedia_utils/logging/config.py +64 -0
  24. winipedia_utils/logging/logger.py +26 -0
  25. winipedia_utils/modules/__init__.py +1 -0
  26. winipedia_utils/modules/class_.py +76 -0
  27. winipedia_utils/modules/function.py +86 -0
  28. winipedia_utils/modules/module.py +361 -0
  29. winipedia_utils/modules/package.py +350 -0
  30. winipedia_utils/oop/__init__.py +1 -0
  31. winipedia_utils/oop/mixins/__init__.py +1 -0
  32. winipedia_utils/oop/mixins/meta.py +315 -0
  33. winipedia_utils/oop/mixins/mixin.py +28 -0
  34. winipedia_utils/os/__init__.py +1 -0
  35. winipedia_utils/os/os.py +61 -0
  36. winipedia_utils/projects/__init__.py +1 -0
  37. winipedia_utils/projects/poetry/__init__.py +1 -0
  38. winipedia_utils/projects/poetry/config.py +91 -0
  39. winipedia_utils/projects/poetry/poetry.py +30 -0
  40. winipedia_utils/setup.py +36 -0
  41. winipedia_utils/testing/__init__.py +1 -0
  42. winipedia_utils/testing/assertions.py +23 -0
  43. winipedia_utils/testing/convention.py +177 -0
  44. winipedia_utils/testing/create_tests.py +286 -0
  45. winipedia_utils/testing/fixtures.py +28 -0
  46. winipedia_utils/testing/tests/__init__.py +1 -0
  47. winipedia_utils/testing/tests/base/__init__.py +1 -0
  48. winipedia_utils/testing/tests/base/fixtures/__init__.py +1 -0
  49. winipedia_utils/testing/tests/base/fixtures/fixture.py +6 -0
  50. winipedia_utils/testing/tests/base/fixtures/scopes/__init__.py +1 -0
  51. winipedia_utils/testing/tests/base/fixtures/scopes/class_.py +33 -0
  52. winipedia_utils/testing/tests/base/fixtures/scopes/function.py +7 -0
  53. winipedia_utils/testing/tests/base/fixtures/scopes/module.py +31 -0
  54. winipedia_utils/testing/tests/base/fixtures/scopes/package.py +7 -0
  55. winipedia_utils/testing/tests/base/fixtures/scopes/session.py +224 -0
  56. winipedia_utils/testing/tests/base/utils/__init__.py +1 -0
  57. winipedia_utils/testing/tests/base/utils/utils.py +82 -0
  58. winipedia_utils/testing/tests/conftest.py +26 -0
  59. winipedia_utils/text/__init__.py +1 -0
  60. winipedia_utils/text/string.py +126 -0
  61. winipedia_utils-0.1.0.dist-info/LICENSE +21 -0
  62. winipedia_utils-0.1.0.dist-info/METADATA +350 -0
  63. winipedia_utils-0.1.0.dist-info/RECORD +64 -0
  64. winipedia_utils-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,334 @@
1
+ """Command utilities for Django.
2
+
3
+ This module provides utility functions for working with Django commands,
4
+ including command execution and output handling. These utilities help with
5
+ managing and automating Django command-line tasks.
6
+ """
7
+
8
+ import logging
9
+ from abc import abstractmethod
10
+ from argparse import ArgumentParser
11
+ from typing import Any, final
12
+
13
+ from django.core.management import BaseCommand
14
+
15
+ from winipedia_utils.oop.mixins.mixin import ABCImplementationLoggingMixin
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class ABCBaseCommand(ABCImplementationLoggingMixin, BaseCommand):
21
+ """Abstract base class for Django management commands with logging and validation.
22
+
23
+ This class serves as a foundation for creating Django management commands that
24
+ require abstract method implementation enforcement and automatic logging.
25
+ It combines Django's BaseCommand with ABCImplementationLoggingMixin to provide
26
+ both command functionality and development-time validation.
27
+
28
+ The class implements a template method pattern where common argument handling
29
+ and execution flow are managed by final methods, while specific implementations
30
+ are defined through abstract methods that subclasses must implement.
31
+
32
+ Key Features:
33
+ - Automatic logging of method calls with performance tracking
34
+ - Compile-time validation that all abstract methods are implemented
35
+ - Structured argument handling with base and custom arguments
36
+ - Template method pattern for consistent command execution flow
37
+
38
+ Inheritance Order:
39
+ The order of inheritance is critical: ABCImplementationLoggingMixin must
40
+ come before BaseCommand because Django's BaseCommand doesn't call
41
+ super().__init__(), so the mixin's metaclass initialization must happen
42
+ first to ensure proper class construction.
43
+
44
+ Example:
45
+ >>> class MyCommand(ABCBaseCommand):
46
+ ... def add_command_arguments(self, parser):
47
+ ... parser.add_argument('--my-option', help='Custom option')
48
+ ...
49
+ ... def handle_command(self, *args, **options):
50
+ ... self.stdout.write('Executing my command')
51
+
52
+ Note:
53
+ - All methods are automatically logged with performance tracking
54
+ - Subclasses must implement add_command_arguments and handle_command
55
+ - The @final decorator prevents overriding of template methods
56
+ """
57
+
58
+ @final
59
+ def add_arguments(self, parser: ArgumentParser) -> None:
60
+ """Configure command-line arguments for the Django management command.
61
+
62
+ This method implements the template method pattern by first adding common
63
+ base arguments that are used across multiple commands, then delegating
64
+ to the abstract add_command_arguments method for command-specific arguments.
65
+
66
+ The @final decorator prevents subclasses from overriding this method,
67
+ ensuring consistent argument handling across all commands while still
68
+ allowing customization through the abstract method.
69
+
70
+ Args:
71
+ parser (ArgumentParser): Django's argument parser instance used to
72
+ define command-line options and arguments for the command.
73
+
74
+ Note:
75
+ - This method is final and cannot be overridden by subclasses
76
+ - Common arguments are added first via _add_arguments()
77
+ - Custom arguments are added via the abstract add_command_arguments()
78
+ - Subclasses must implement add_command_arguments() for specific needs
79
+ """
80
+ # add base args that are used in most commands
81
+ self._add_arguments(parser)
82
+
83
+ # add additional args that are specific to the command
84
+ self.add_command_arguments(parser)
85
+
86
+ @final
87
+ def _add_arguments(self, parser: ArgumentParser) -> None:
88
+ """Add common command-line arguments used across multiple commands.
89
+
90
+ This method defines base arguments that are commonly used across different
91
+ Django management commands. These arguments provide standard functionality
92
+ like dry-run mode, verbosity control, and batch processing options.
93
+
94
+ The method is final to ensure consistent base argument handling, while
95
+ command-specific arguments are handled through the abstract
96
+ add_command_arguments method.
97
+
98
+ Args:
99
+ parser (ArgumentParser): Django's argument parser instance to which
100
+ common arguments should be added.
101
+
102
+ Note:
103
+ - Provides standard arguments for dry-run, verbosity, and batch processing
104
+ - The @final decorator prevents subclasses from overriding this method
105
+ - Command-specific arguments should be added via add_command_arguments()
106
+ """
107
+ parser.add_argument(
108
+ "--dry-run",
109
+ action="store_true",
110
+ help="Show what would be done without actually executing the changes",
111
+ )
112
+
113
+ parser.add_argument(
114
+ "--size",
115
+ type=int,
116
+ default=None,
117
+ help="Size of smth in a command",
118
+ )
119
+
120
+ parser.add_argument(
121
+ "--force",
122
+ action="store_true",
123
+ help="Force an action in a command",
124
+ )
125
+
126
+ parser.add_argument(
127
+ "--delete",
128
+ action="store_true",
129
+ help="Deleting smth in a command",
130
+ )
131
+
132
+ parser.add_argument(
133
+ "--quiet",
134
+ action="store_true",
135
+ help="Suppress non-error output for cleaner automation",
136
+ )
137
+
138
+ parser.add_argument(
139
+ "--debug",
140
+ action="store_true",
141
+ help="Print debug output for detailed tracing",
142
+ )
143
+
144
+ parser.add_argument(
145
+ "--yes",
146
+ action="store_true",
147
+ help="Answer yes to all prompts",
148
+ default=False,
149
+ )
150
+
151
+ parser.add_argument(
152
+ "--config",
153
+ type=str,
154
+ help="A configuration setup like filepath or json string for a command",
155
+ default=None,
156
+ )
157
+
158
+ parser.add_argument(
159
+ "--timeout",
160
+ type=int,
161
+ help="Timeout for a command",
162
+ default=None,
163
+ )
164
+
165
+ parser.add_argument(
166
+ "--batch-size",
167
+ type=int,
168
+ default=None,
169
+ help="Number of items to process in each batch",
170
+ )
171
+
172
+ parser.add_argument(
173
+ "--no-input",
174
+ action="store_true",
175
+ help="Do not prompt for user input",
176
+ )
177
+
178
+ parser.add_argument(
179
+ "--threads",
180
+ type=int,
181
+ default=None,
182
+ help="Number of threads to use for processing",
183
+ )
184
+
185
+ parser.add_argument(
186
+ "--processes",
187
+ type=int,
188
+ default=None,
189
+ help="Number of processes to use for processing",
190
+ )
191
+
192
+ @abstractmethod
193
+ def add_command_arguments(self, parser: ArgumentParser) -> None:
194
+ """Add command-specific arguments to the argument parser.
195
+
196
+ This abstract method must be implemented by subclasses to define
197
+ command-specific command-line arguments. It is called after common
198
+ base arguments are added, allowing each command to customize its
199
+ argument interface while maintaining consistent base functionality.
200
+
201
+ Subclasses should use this method to add arguments specific to their
202
+ command's functionality, such as file paths, configuration options,
203
+ or operational flags.
204
+
205
+ Args:
206
+ parser (ArgumentParser): Django's argument parser instance to which
207
+ command-specific arguments should be added.
208
+
209
+ Example:
210
+ >>> def add_command_arguments(self, parser):
211
+ ... parser.add_argument(
212
+ ... '--input-file',
213
+ ... type=str,
214
+ ... required=True,
215
+ ... help='Path to input file'
216
+ ... )
217
+ ... parser.add_argument(
218
+ ... '--output-format',
219
+ ... choices=['json', 'csv', 'xml'],
220
+ ... default='json',
221
+ ... help='Output format for results'
222
+ ... )
223
+
224
+ Note:
225
+ - This method is abstract and must be implemented by subclasses
226
+ - Called after _add_arguments() adds common base arguments
227
+ - Should focus on command-specific functionality only
228
+ """
229
+
230
+ @final
231
+ def handle(self, *args: Any, **options: Any) -> None:
232
+ """Execute the Django management command using template method pattern.
233
+
234
+ This method implements the main execution flow for the command by first
235
+ calling common handling logic through _handle(), then delegating to
236
+ the command-specific implementation via handle_command().
237
+
238
+ The @final decorator ensures this execution pattern cannot be overridden,
239
+ maintaining consistent command execution flow while allowing customization
240
+ through the abstract handle_command method.
241
+
242
+ Args:
243
+ *args: Positional arguments passed from Django's command execution.
244
+ **options: Keyword arguments containing parsed command-line options
245
+ and their values as defined by add_arguments().
246
+
247
+ Note:
248
+ - This method is final and cannot be overridden by subclasses
249
+ - Common handling logic is executed first via _handle()
250
+ - Command-specific logic is executed via abstract handle_command()
251
+ - All method calls are automatically logged with performance tracking
252
+ """
253
+ self._handle(*args, **options)
254
+ self.handle_command(*args, **options)
255
+
256
+ @final
257
+ def _handle(self, *_args: Any, **options: Any) -> None:
258
+ """Execute common handling logic shared across all commands.
259
+
260
+ This method is intended to contain common processing logic that should
261
+ be executed before command-specific handling. Currently, it serves as
262
+ a placeholder for future common functionality such as logging setup,
263
+ validation, or shared initialization.
264
+
265
+ The method is final to ensure consistent common handling across all
266
+ commands, while command-specific logic is handled through the abstract
267
+ handle_command method.
268
+
269
+ Args:
270
+ *args: Positional arguments passed from Django's command execution.
271
+ Currently unused but reserved for future common processing.
272
+ **options: Keyword arguments containing parsed command-line options.
273
+ Currently unused but reserved for future common processing.
274
+
275
+ Note:
276
+ - Examples might include logging setup, database connection validation, etc.
277
+ - The @final decorator prevents subclasses from overriding this method
278
+ - Called before handle_command() in the template method pattern
279
+ """
280
+ # log each option for the command
281
+ for key, value in options.items():
282
+ logger.info(
283
+ "Command '%s' - runs with option: '%s' with value: '%s'",
284
+ self.__class__.__name__,
285
+ key,
286
+ value,
287
+ )
288
+
289
+ @abstractmethod
290
+ def handle_command(self, *args: Any, **options: Any) -> None:
291
+ """Execute command-specific logic and functionality.
292
+
293
+ This abstract method must be implemented by subclasses to define the
294
+ core functionality of the Django management command. It is called after
295
+ common handling logic is executed, allowing each command to implement
296
+ its specific business logic while benefiting from shared infrastructure.
297
+
298
+ This method should contain the main logic that the command is designed
299
+ to perform, such as data processing, database operations, file manipulation,
300
+ or any other command-specific tasks.
301
+
302
+ Args:
303
+ *args: Positional arguments passed from Django's command execution.
304
+ These are typically not used in Django management commands.
305
+ **options: Keyword arguments containing parsed command-line options
306
+ and their values as defined by add_command_arguments().
307
+
308
+ Example:
309
+ >>> def handle_command(self, *args, **options):
310
+ ... input_file = options['input_file']
311
+ ... dry_run = options['dry_run'] # Base argument
312
+ ... batch_size = options['batch_size'] # Base argument
313
+ ... quiet = options['quiet'] # Base argument
314
+ ...
315
+ ... if dry_run:
316
+ ... self.stdout.write('Dry run mode - no changes will be made')
317
+ ...
318
+ ... if not quiet:
319
+ ... msg = f'Processing {input_file} in batches of {batch_size}'
320
+ ... self.stdout.write(msg)
321
+ ...
322
+ ... # Perform command-specific operations
323
+ ... self.process_file(input_file, batch_size, dry_run)
324
+ ...
325
+ ... if not quiet:
326
+ ... self.stdout.write('Command completed successfully')
327
+
328
+ Note:
329
+ - This method is abstract and must be implemented by subclasses
330
+ - Called after _handle() executes common logic
331
+ - Should contain the main functionality of the command
332
+ - All method calls are automatically logged with performance tracking
333
+ - Use self.stdout.write() for output instead of print()
334
+ """
@@ -0,0 +1,304 @@
1
+ """Database utilities for Django.
2
+
3
+ This module provides utility functions for working with Django models,
4
+ including hashing, topological sorting, and database operations.
5
+ These utilities help with efficient and safe database interactions.
6
+ """
7
+
8
+ from datetime import datetime
9
+ from graphlib import TopologicalSorter
10
+ from typing import TYPE_CHECKING, Any, Self
11
+
12
+ from django.contrib.contenttypes.fields import GenericForeignKey
13
+ from django.db import connection
14
+ from django.db.models import DateTimeField, Field, Model
15
+ from django.db.models.fields.related import ForeignKey, ForeignObjectRel
16
+ from django.forms.models import model_to_dict
17
+
18
+ from winipedia_utils.logging.logger import get_logger
19
+ from winipedia_utils.text.string import split_on_uppercase
20
+
21
+ if TYPE_CHECKING:
22
+ from django.db.models.options import Options
23
+
24
+ logger = get_logger(__name__)
25
+
26
+
27
+ def get_model_meta(model: type[Model]) -> "Options[Model]":
28
+ """Get the Django model metadata options object.
29
+
30
+ Retrieves the _meta attribute from a Django model class, which contains
31
+ metadata about the model including field definitions, table name, and
32
+ other model configuration options. This is a convenience wrapper around
33
+ accessing the private _meta attribute directly.
34
+
35
+ Args:
36
+ model (type[Model]): The Django model class to get metadata from.
37
+
38
+ Returns:
39
+ Options[Model]: The model's metadata options object containing
40
+ field definitions, table information, and other model configuration.
41
+
42
+ Example:
43
+ >>> from django.contrib.auth.models import User
44
+ >>> meta = get_model_meta(User)
45
+ >>> meta.db_table
46
+ 'auth_user'
47
+ >>> len(meta.get_fields())
48
+ 11
49
+ """
50
+ return model._meta # noqa: SLF001
51
+
52
+
53
+ def get_fields(
54
+ model: type[Model],
55
+ ) -> list[Field[Any, Any] | ForeignObjectRel | GenericForeignKey]:
56
+ """Get all fields from a Django model including relationships.
57
+
58
+ Retrieves all field objects from a Django model, including regular fields,
59
+ foreign key relationships, reverse foreign key relationships, and generic
60
+ foreign keys. This provides a comprehensive view of all model attributes
61
+ that can be used for introspection, validation, or bulk operations.
62
+
63
+ Args:
64
+ model (type[Model]): The Django model class to get fields from.
65
+
66
+ Returns:
67
+ list[Field | ForeignObjectRel | GenericForeignKey]: A list
68
+ containing all field objects associated with the model, including:
69
+ - Regular model fields (CharField, IntegerField, etc.)
70
+ - Foreign key fields (ForeignKey, OneToOneField, etc.)
71
+ - Reverse relationship fields (ForeignObjectRel)
72
+ - Generic foreign key fields (GenericForeignKey)
73
+
74
+ Example:
75
+ >>> from django.contrib.auth.models import User
76
+ >>> fields = get_fields(User)
77
+ >>> field_names = [f.name for f in fields if hasattr(f, 'name')]
78
+ >>> 'username' in field_names
79
+ True
80
+ >>> 'email' in field_names
81
+ True
82
+ """
83
+ return get_model_meta(model).get_fields()
84
+
85
+
86
+ def get_field_names(
87
+ fields: list[Field[Any, Any] | ForeignObjectRel | GenericForeignKey],
88
+ ) -> list[str]:
89
+ """Get the names of all fields from a Django model including relationships.
90
+
91
+ Retrieves the names of all field objects from a Django model, including
92
+ regular fields, foreign key relationships, reverse foreign key relationships,
93
+ and generic foreign keys. This provides a comprehensive view of all model
94
+ attributes that can be used for introspection, validation, or bulk operations.
95
+
96
+ Args:
97
+ fields (list[Field | ForeignObjectRel | GenericForeignKey]):
98
+ The list of field objects to get names from.
99
+
100
+ Returns:
101
+ list[str]: A list containing the names of all fields.
102
+
103
+ Example:
104
+ >>> from django.contrib.auth.models import User
105
+ >>> fields = get_fields(User)
106
+ >>> field_names = get_field_names(fields)
107
+ >>> 'username' in field_names
108
+ True
109
+ >>> 'email' in field_names
110
+ True
111
+ """
112
+ return [field.name for field in fields]
113
+
114
+
115
+ def topological_sort_models(models: list[type[Model]]) -> list[type[Model]]:
116
+ """Sort Django models in dependency order using topological sorting.
117
+
118
+ Analyzes foreign key relationships between Django models and returns them
119
+ in an order where dependencies come before dependents. This ensures that
120
+ when performing operations like bulk creation or deletion, models are
121
+ processed in the correct order to avoid foreign key constraint violations.
122
+
123
+ The function uses Python's graphlib.TopologicalSorter to perform the sorting
124
+ based on ForeignKey relationships between the provided models. Only
125
+ relationships between models in the input list are considered.
126
+
127
+ Args:
128
+ models (list[type[Model]]): A list of Django model classes to sort
129
+ based on their foreign key dependencies.
130
+
131
+ Returns:
132
+ list[type[Model]]: The input models sorted in dependency order, where
133
+ models that are referenced by foreign keys appear before models
134
+ that reference them. Self-referential relationships are ignored.
135
+
136
+ Raises:
137
+ graphlib.CycleError: If there are circular dependencies between models
138
+ that cannot be resolved.
139
+
140
+ Example:
141
+ >>> # Assuming Author model has no dependencies
142
+ >>> # and Book model has ForeignKey to Author
143
+ >>> models = [Book, Author]
144
+ >>> sorted_models = topological_sort_models(models)
145
+ >>> sorted_models
146
+ [<class 'Author'>, <class 'Book'>]
147
+
148
+ Note:
149
+ - Only considers ForeignKey relationships, not other field types
150
+ - Self-referential foreign keys are ignored to avoid self-loops
151
+ - Only relationships between models in the input list are considered
152
+ """
153
+ ts: TopologicalSorter[type[Model]] = TopologicalSorter()
154
+
155
+ for model in models:
156
+ deps = {
157
+ field.related_model
158
+ for field in get_fields(model)
159
+ if isinstance(field, ForeignKey)
160
+ and isinstance(field.related_model, type)
161
+ and field.related_model in models
162
+ and field.related_model is not model
163
+ }
164
+ ts.add(model, *deps)
165
+
166
+ return list(ts.static_order())
167
+
168
+
169
+ def execute_sql(
170
+ sql: str, params: dict[str, Any] | None = None
171
+ ) -> tuple[list[str], list[Any]]:
172
+ """Execute raw SQL query and return column names with results.
173
+
174
+ Executes a raw SQL query using Django's database connection and returns
175
+ both the column names and the result rows. This provides a convenient
176
+ way to run custom SQL queries while maintaining Django's database
177
+ connection management and parameter binding for security.
178
+
179
+ The function automatically handles cursor management and ensures proper
180
+ cleanup of database resources. Parameters are safely bound to prevent
181
+ SQL injection attacks.
182
+
183
+ Args:
184
+ sql (str): The SQL query string to execute. Can contain parameter
185
+ placeholders that will be safely bound using the params argument.
186
+ params (dict[str, Any] | None, optional): Dictionary of parameters
187
+ to bind to the SQL query for safe parameter substitution.
188
+ Defaults to None if no parameters are needed.
189
+
190
+ Returns:
191
+ tuple[list[str], list[Any]]: A tuple containing:
192
+ - list[str]: Column names from the query result
193
+ - list[Any]: List of result rows, where each row is a tuple
194
+ of values corresponding to the column names
195
+
196
+ Raises:
197
+ django.db.Error: If there's a database error during query execution
198
+ django.db.ProgrammingError: If the SQL syntax is invalid
199
+ django.db.IntegrityError: If the query violates database constraints
200
+
201
+ Example:
202
+ >>> sql = "SELECT id, username FROM auth_user WHERE is_active = %(active)s"
203
+ >>> params = {"active": True}
204
+ >>> columns, rows = execute_sql(sql, params)
205
+ >>> columns
206
+ ['id', 'username']
207
+ >>> rows[0]
208
+ (1, 'admin')
209
+
210
+ Note:
211
+ - Uses Django's default database connection
212
+ - Automatically manages cursor lifecycle
213
+ - Parameters are safely bound to prevent SQL injection
214
+ - Returns all results in memory - use with caution for large datasets
215
+ """
216
+ with connection.cursor() as cursor:
217
+ cursor.execute(sql=sql, params=params)
218
+ rows = cursor.fetchall()
219
+ column_names = [col[0] for col in cursor.description]
220
+
221
+ return column_names, rows
222
+
223
+
224
+ def hash_model_instance(
225
+ instance: Model,
226
+ fields: list[Field[Any, Any] | ForeignObjectRel | GenericForeignKey],
227
+ ) -> int:
228
+ """Hash a model instance based on its field values.
229
+
230
+ Generates a hash for a Django model instance by considering the values
231
+ of its fields. This can be useful for comparing instances, especially
232
+ when dealing with related objects or complex data structures. The hash
233
+ is generated by recursively hashing related objects up to a specified
234
+ depth.
235
+ This is not very reliable, use with caution.
236
+ Only use if working with unsafed objects or bulks, as with safed
237
+
238
+ Args:
239
+ instance (Model): The Django model instance to hash
240
+ fields (list[str]): The fields to hash
241
+
242
+ Returns:
243
+ int: The hash value representing the instance's data
244
+
245
+ """
246
+ if instance.pk:
247
+ return hash(instance.pk)
248
+
249
+ field_names = get_field_names(fields)
250
+ model_dict = model_to_dict(instance, fields=field_names)
251
+ sorted_dict = dict(sorted(model_dict.items()))
252
+ values = (type(instance), tuple(sorted_dict.items()))
253
+ return hash(values)
254
+
255
+
256
+ class BaseModel(Model):
257
+ """Base model for all models in the project.
258
+
259
+ Provides common fields and methods for all models.
260
+ """
261
+
262
+ created_at: DateTimeField[datetime, datetime] = DateTimeField(auto_now_add=True)
263
+ updated_at: DateTimeField[datetime, datetime] = DateTimeField(auto_now=True)
264
+
265
+ class Meta:
266
+ """Mark the model as abstract."""
267
+
268
+ # abstract does not inherit in children
269
+ abstract = True
270
+ # the rest does inherit
271
+ verbose_name = "Base Model"
272
+ verbose_name_plural = "Base Models"
273
+
274
+ def __str__(self) -> str:
275
+ """Base string representation of a model.
276
+
277
+ Returns:
278
+ str: The string representation of the model as all fields and their values.
279
+ """
280
+ fields_values = ", ".join(
281
+ f"{field.name}={getattr(self, field.name)}"
282
+ for field in get_fields(self.__class__)
283
+ )
284
+ return f"{self.__class__.__name__}({fields_values})"
285
+
286
+ def __repr__(self) -> str:
287
+ """Base representation of a model."""
288
+ return str(self)
289
+
290
+ @property
291
+ def meta(self) -> "Options[Self]":
292
+ """Get the meta options for the model."""
293
+ return self._meta
294
+
295
+ @classmethod
296
+ def make_verbose_name(cls) -> str:
297
+ """Make a verbose name for the model."""
298
+ # split by upper case letters
299
+ return " ".join(split_on_uppercase(cls.__name__)).title()
300
+
301
+ @classmethod
302
+ def make_verbose_name_plural(cls) -> str:
303
+ """Make a verbose name plural for the model."""
304
+ return cls.make_verbose_name() + "s"
@@ -0,0 +1 @@
1
+ """__init__ module for winipedia_utils.git."""