You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
64 lines
2.3 KiB
64 lines
2.3 KiB
from django.db import models
|
|
from django.utils.timezone import now
|
|
|
|
class BaseModel(models.Model):
|
|
creation_date = models.DateTimeField(default=now, editable=False)
|
|
last_update = models.DateTimeField(default=now)
|
|
|
|
class Meta:
|
|
abstract = True
|
|
|
|
def get_parent_reference(self):
|
|
"""Override in child models to provide parent reference"""
|
|
return None, None
|
|
|
|
def get_children_by_model(self):
|
|
"""
|
|
Returns a dictionary where:
|
|
- keys are the model names
|
|
- values are QuerySets of related objects
|
|
"""
|
|
children = self._meta.get_fields(include_parents=False, include_hidden=False)
|
|
related_objects = {}
|
|
|
|
for child in children:
|
|
if (child.one_to_many or child.one_to_one) and child.auto_created:
|
|
model_name = child.related_model.__name__
|
|
related_objects[model_name] = getattr(self, child.name).all()
|
|
|
|
return related_objects
|
|
|
|
def get_parents_by_model(self):
|
|
"""
|
|
Returns a dictionary where:
|
|
- keys are the model names
|
|
- values are the parent model instances
|
|
"""
|
|
parents = {}
|
|
|
|
# Get all fields including parent links
|
|
fields = self._meta.get_fields(include_parents=True, include_hidden=True)
|
|
|
|
for field in fields:
|
|
# Check if the field is a parent link (OneToOne field that points to a parent model)
|
|
if isinstance(field, models.OneToOneRel) and field.parent_link:
|
|
model_name = field.related_model.__name__
|
|
# Get the parent instance using the related name
|
|
parent_instance = getattr(self, field.get_accessor_name())
|
|
if parent_instance:
|
|
parents[model_name] = parent_instance
|
|
|
|
# Also check for direct foreign key relationships that might represent parent relationships
|
|
elif isinstance(field, models.ForeignKey):
|
|
model_name = field.related_model.__name__
|
|
parent_instance = getattr(self, field.name)
|
|
if parent_instance:
|
|
parents[model_name] = parent_instance
|
|
|
|
return parents
|
|
|
|
class SideStoreModel(BaseModel):
|
|
store_id = models.CharField(max_length=100)
|
|
|
|
class Meta:
|
|
abstract = True
|
|
|