如何在保存到数据库之前在条目中创建过滤器?

时间:2013-05-02 05:35:30

标签: django django-models django-admin

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

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

这是我的model.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'

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

1 个答案:

答案 0 :(得分: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的替代方案,您可以编写自己的自定义表单。优点是您可以显示自定义错误消息并执行多个非标准验证,即使是很多ToMany。

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在db-level上。无法进行不希望的输入。表单处于验证级别。所以de db可以接受不需要的条目。但是这种形式永远不会提交。其他形式或逻辑可以!