0

我将如何做?我是 Django 的新手。我已经阅读了很多,但对我来说仍然无法理解。我正在创建一个科目注册模型。我希望它以这种方式过滤:

如果 student_id 存在,则查找主题和课程项(如果存在)将显示错误消息“已存在”,否则将保存条目。

这是我的模型.py

class SubjectsEnrolled(models.Model):
    student =  models.ForeignKey(Student)
    STATUS = (
        ('1', 'Passed'),
        ('2', 'Failed'),
        ('3', 'No Grade'),
        ('4', 'Incomplete'),
    )
    subject = models.ForeignKey(Subject)
    grade = models.DecimalField(max_digits=4, decimal_places=2, blank=True, null=True)
    status = models.CharField(max_length=2, choices=STATUS, blank=True, null=True)
    schoolterm = models.ForeignKey(SchoolTerm)

这是我的 admin.py

class SubjectsEnrolledAdmin(admin.ModelAdmin):
    list_display = ('student', 'get_student_lastname', 'get_student_firstname', 'get_student_course', 'subject', 'grade', 'status','schoolterm')

    search_fields = ['student__student_id','student__last_name', 'student__course__course', 'schoolterm__schoolterm']

    def get_student_lastname(self, instance):
        return instance.student.last_name
    get_student_lastname.short_description = 'Last Name'

    def get_student_firstname(self, instance):
        return instance.student.first_name
    get_student_firstname.short_description = 'First Name'

    def get_student_course(self, instance):
        return instance.student.course
    get_student_course.short_description = 'Course'

希望对此有答案...谢谢...

4

1 回答 1

0

对于唯一性,使用 de Model Meta 选项 unique_together。在您的模型中:

class SubjectsEnrolled(models.Model):
    student =  models.ForeignKey(Student)
    ...
    schoolterm = models.ForeignKey(SchoolTerm)

    class Meta:
        unique_together = (("student", "schoolterm"),)

https://docs.djangoproject.com/en/dev/ref/models/options/#django.db.models.Options.unique_together注意: manyToManyField 不能包含在 unique_together 中!

作为 unique_together 的替代方案,您可以编写自己的自定义表单。优点是您可以显示自定义错误消息并进行多次非标准验证,甚至是多对多。

1)在 admin.py 创建一个自定义表单:

class SubjectsEnrolledForm(forms.Form):
    def clean(self):
        cleaned_data = super(SubjectsEnrolledForm, self).clean()
        student = cleaned_data.get("student")
        schoolterm = cleaned_data.get("schoolterm")
        if student and schoolterm:
            # Only do something if both fields are valid so far.
            if student in schoolterm.student_set.all():
                raise forms.ValidationError("Student %s in %s term!"%
                                                 (student, schoolterm))

        # Always return the full collection of cleaned data.
        return cleaned_data

2)在 Admin.py 创建你的 ModelAdmin 并指定形式:

class SubjectsEnrolledAdmin(admin.ModelAdmin):
    form = SubjectsEnrolledForm
    ...

注意:unique_together 在数据库级别。不能进行不受欢迎的条目。该表单处于验证级别。所以 de db 可以接受不需要的条目。但是这个表格永远不会提交。其他形式或逻辑可以!

于 2013-05-03T12:41:23.403 回答