Django抽象基类模型子类save方法与父类方法兼容实现问题
save() via super() in Your Child Class Hey there! The issue you're hitting is super common when overriding methods in Django models (or any Python class, really)—when you redefine the save() method in your child class, it won’t automatically run the parent class’s implementation unless you explicitly trigger it.
Here’s how to fix it, depending on when you want your child-specific operations to execute:
Option 1: Run Child Operations Before Parent Save Logic
If you need your custom code to run before the parent handles setting created_by/updated_by and saving to the database, structure your child’s save() like this:
class Child(BaseModel): # Add your child model fields here title = models.CharField(max_length=200) def save(self, *args, **kwargs): # Step 1: Execute your child-specific operations first print("Running custom pre-save logic for Child model") # Example: Auto-set title if it's empty if not self.title: self.title = f"Untitled {self.__class__.__name__}" # Step 2: Explicitly call the parent BaseModel's save method super().save(*args, **kwargs)
Option 2: Run Child Operations After Parent Save Logic
If your custom code needs to execute after the parent has saved the record (like updating a related object or logging), call super() first:
class Child(BaseModel): # Add your child model fields here title = models.CharField(max_length=200) def save(self, *args, **kwargs): # Step 1: First run BaseModel's save logic (handles timestamps and user fields) super().save(*args, **kwargs) # Step 2: Now run your child-specific post-save operations print("Running custom post-save logic for Child model") # Example: Log the save event from datetime import datetime with open("child_save_logs.txt", "a") as log_file: log_file.write(f"Child record {self.pk} saved at {datetime.now()}\n")
Why This Works
The super() function in Python lets you access methods from the parent class (in this case, BaseModel) without hardcoding its name. By calling super().save(*args, **kwargs), you’re telling Python to run the save() logic defined in your abstract base class—including setting created_by/updated_by and the actual database save—while retaining your child’s custom behavior.
Key Note About the user Parameter
Your BaseModel extracts the user from kwargs to set ownership fields. Make sure you pass through all args and kwargs when calling super().save() so the parent class can handle the user parameter correctly if it’s provided.
内容的提问来源于stack exchange,提问作者rahnama7m

