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

Django新手求助:Charity与Benefactor模型实现及继承问题

Fixing Your Django Charity Platform Models: Inheritance & Field Issues

Hey Amir, let's break down the issues with your models and get them sorted out. As a Django beginner, it's common to trip up on inheritance and field rules—let's tackle this step by step.

1. First: Fix the User Model Inheritance

You're inheriting from AbstractUser, which already includes most of the fields you've redefined. Redefining these fields causes conflicts because Django expects the parent class's fields to be used. Let's trim this down to only your custom fields:

# accounts/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import AbstractUserManager

class User(AbstractUser):
    gender_status = [
        ('M','Male'),
        ('F','Female'),
    ]
    # 👇 These fields are *inherited from AbstractUser* (marked in italics)
    # *id*, *date_joined*, *is_active*, *is_staff*, *is_superuser*, *last_login*,
    # *email*, *first_name*, *last_name*, *password*, *username*
    
    # Custom optional fields (marked as "light" per your rules)
    address = models.TextField(blank=True, null=True)
    age = models.PositiveSmallIntegerField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    gender = models.CharField(max_length=1, choices=gender_status, blank=True, null=True)
    phone = models.CharField(max_length=15, blank=True, null=True)

    # Keep the default manager from AbstractUser
    objects = AbstractUserManager()

Important: Don't forget to add AUTH_USER_MODEL = 'accounts.User' in your project's settings.py—this tells Django to use your custom User model instead of the default one.

2. Clean Up Benefactor & Charity Models

Your OneToOne relationships to User are on the right track, but let's clarify fields per your rules and fix small issues:

# charities/models.py
from django.db import models
from accounts.models import User

class Benefactor(models.Model):
    ex_status = [
        (0,'beginner'),
        (1,'middle'),
        (2,'expert'),
    ]
    # **id** is auto-generated by Django (you don't need to define it explicitly)
    **user** = models.OneToOneField(User, on_delete=models.CASCADE)  # Bold: Primary key relation
    experience = models.SmallIntegerField(choices=ex_status, default=0)  # Fixed typo: "exprience" → "experience"
    free_time_per_week = models.PositiveSmallIntegerField(default=0)

class Charity(models.Model):
    # **id** is auto-generated by Django
    **user** = models.OneToOneField(User, on_delete=models.CASCADE)  # Bold: Primary key relation
    name = models.CharField(max_length=50)  # Required field
    reg_number = models.CharField(max_length=10)  # Required field

Note: Django automatically creates a BigAutoField primary key (id) for every model unless you explicitly define one—you can safely remove the commented-out id lines to keep things clean.

3. Fix the Task Model

There are a few key issues here: a typo in the foreign key field, missing optional field settings, and clarifying required vs optional fields:

class Task(models.Model):
    state_status = [
        ("P" , "pending"),
        ("W", "Waiting"),
        ("A", "Assigned"),
        ("D", "Done")
    ]
    gender_limit_status = [
        ("M","Male"),
        ("F","Female"),
    ]
    # **id** is auto-generated by Django (you can remove your explicit definition)
    **assigned_benefactor** = models.ForeignKey(Benefactor, on_delete=models.CASCADE)  # Fixed typo: "bonefactor" → "benefactor" (Bold: Foreign key)
    **charity** = models.ForeignKey(Charity, on_delete=models.CASCADE)  # Bold: Foreign key relation
    age_limit_from = models.IntegerField(blank=True, null=True)  # Optional field (light)
    age_limit_to = models.IntegerField(blank=True, null=True)  # Optional field (light)
    date = models.DateField(blank=True, null=True)  # Optional field (light)
    description = models.TextField(blank=True, null=True)  # Optional field (light)
    gender_limit = models.CharField(choices=gender_limit_status, max_length=1, blank=True, null=True)  # Made optional (light)
    state = models.CharField(max_length=1, choices=state_status, default='P')  # Required field with default
    title = models.CharField(max_length=100)  # Required field

Key Takeaways Matching Your Field Rules

Let's align the corrected models with your specified rules:

  • Bold fields: These are your key relations (ForeignKey/OneToOneField) like **user** (Benefactor/Charity), **assigned_benefactor**, **charity** (Task).
  • Italic fields: These are inherited from AbstractUser in your User model (e.g., username, email, date_joined).
  • Optional (light) fields: Marked with blank=True, null=True (e.g., address, age, gender_limit, date).

Final Checks

  1. Run python manage.py makemigrations to create migration files for your corrected models.
  2. Run python manage.py migrate to apply these changes to your database.
  3. Test creating instances of each model to ensure relations work (e.g., create a User, then a Benefactor linked to that User).

内容的提问来源于stack exchange,提问作者Amir Abbas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:02:31