You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django抽象基类模型子类save方法与父类方法兼容实现问题

Solution: Call Parent Class's 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 10:47:55