是否可以使用外键关系将模型的多个字段的主键值保存到另一个模型的单个“字段”中?

时间:2015-07-17 06:41:21

标签: python django django-rest-framework

models.py:

import datetime
from django.db import models
from pygments.lexers import get_all_lexers


LEXERS = [item for item in get_all_lexers() if item[1]]

class Classname(models.Model):
    class_name = models.CharField(max_length=8)
    def __str__(self):
        return self.class_name

class Sectionname(models.Model):
    class_name = models.ForeignKey(Classname)
    section_name = models.CharField(max_length=1, default='A')
    def __str__(self):
        return self.section_name

class Teachername(models.Model):
    field = """ I want to define here a foreign key field(inherited from Sectionname model)which saves the primary key value of row corresponding to two fields (class_name, section_name) above."""
    teachname = models.CharField(max_length=50, verbose_name='teacher Name')
    def __str__(self):
        return self.teachname

class Attendancename(models.Model):
    teacher_name = models.ForeignKey(Teachername)
    date = models.DateField('Date')
    intime = models.TimeField('IN-TIME')
    outtime = models.TimeField('OUT-TIME')

    def hours_conversion(self):
        tdelta = (datetime.datetime.combine(datetime.date.today(),self.outtime) - datetime.datetime.combine(datetime.date.today(),self.intime))
        hours, minutes = tdelta.seconds//3600, (tdelta.seconds//60)%60
    return '{0}hrs {1}mins'.format(hours, minutes)

    def __str__(self):
        return "%s" %self.teacher_name

forms.py:

from django import forms
from django.forms import ModelForm
from .models import Classname, Sectionname, Teachername, Attendancename

class ClassnameForm(ModelForm):
    class_name = forms.CharField(max_length=8)
    class Meta:
        model = Classname
        fields = ('class_name',)

class SectionnameForm(ModelForm):
    class_name = forms.ModelChoiceField(queryset=Classname.objects.all())
    class Meta:
        model = Sectionname
        fields = ('section_name', 'class_name',)

class TeachernameForm(ModelForm):
    field = """ Here I also want to do the same thing, I tried to make a form field, which shows value of both 'section_name' and 'class_name' from above model but only saves the value of corresponding row's primary key."""
    class Meta:
        model = Teachername
        fields = ('classname', 'secname', 'teachname',)

class AttendancenameForm(ModelForm):
    teacher_name = forms.ModelChoiceField(queryset=Teachername.objects.all())
    class Meta:
        model = Attendancename
        fields = ('teacher_name', 'date', 'intime', 'outtime',)

我正在尝试将Sectionname模型字段('calss_name''section_name')的'pk'值保存到Terachername模型的单个'field'中,我还想显示这两个值对于使用表单字段'field'的用户,但仅限于场景,只需要保存主键值。

有可能这样做吗?如果是,那么我该如何在我的应用程序中实现它呢?

请!提供你的建议......

谢谢!提前.....

1 个答案:

答案 0 :(得分:2)

无法将两个外键存储到一个models.ForeignKey字段中的两个不同的表格中,它实际上没有任何意义(如果原因对您来说不明显)那么你应该学习更多关于关系模型的知识。)

但无论如何:由于Sectionname属于一个Classname,因此除了Sectionname pk之外,您不需要任何其他内容来获取相关的Classname

class Teachername(models.Model):
    sectionname = models.ForeignKey(Sectionname)
    teachname = models.CharField(max_length=50, verbose_name='teacher Name')
    def __str__(self):
        return self.teachname


teacher = Teachername.objects.get(pk=XXX)
print teacher, teacher.sectionname, teacher.sectionname.classname

或者如果教师应该教授多个部分:

class Teachername(models.Model):
    sectionnames = models.ManyToMany(Sectionname)
    teachname = models.CharField(max_length=50, verbose_name='teacher Name')
    def __str__(self):
        return self.teachname

teacher = Teachername.objects.get(pk=XXX)
for sectionname in teacher.sectionnames.all():
    print teacher, sectionname.classname