简体   繁体   English

django:在模型字段中添加多个值

[英]django:adding more than one value in model field

i want to create a app for classroom in which their only one teacher and students can be more than one.a nd student can be in more than one class. 我想为教室创建一个应用程序,在该应用程序中,他们唯一的一名老师和学生可以不止一个。一个学生可以在一个以上的班级中学习。 i want to store usernames of students in one classroom. 我想将学生的用户名存储在一个教室中。 is there any model field i can use to store usernames of students. 我可以使用任何模型字段来存储学生的用户名吗? my code so far: 到目前为止我的代码:

models.py models.py

from django.db import models
from django.conf import settings
# Create your models here.

class classroom(models.Model):
    teacher = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    students = models.CharField(max_length=120)

Create a Student model and add a many to many key to a ClassRoom instance. 创建一个Student模型,并向ClassRoom实例添加多对多键。 In that way you are telling " A student may have several classroom and a classroom may have many students " 这样您就说:“ 一个学生可能有几个教室,一个教室可能有很多学生

class ClassRoom(models.Model):
    teacher = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)


 class Student(models.Model):
    name = models.CharField(max_length=120)
    classroom =  models.ManyToManyField(ClassRoom, related_name="students")

So, if you have a classroom instance and want to get all its student. 因此,如果您有一个classroom实例,并且想让其所有学生参加。 Notice the related_name attribute in the field classroom. 注意现场教室中的related_name属性。

classroom.students.all()

If you don't add related_name attribute, you will need to use _set notation 如果不添加related_name属性,则需要使用_set表示法

classroom.student_set.all()

If you have a student instance and want to get his classroom 如果您有一个学生实例并想上他的教室

student.classroom

TIP: For class model naming, use CamelCase notation. 提示:对于类模型命名,请使用CamelCase表示法。

You should create a separate model for storing students, but even more than that - you should really start with the Django tutorial on their official site. 您应该创建一个单独的模型来存储学生,但不仅限于此-您应该从他们官方站点上的Django教程开始。

But your problem is solved accordingly: 但您的问题已相应解决:

from django.db import models
from django.conf import settings

class ClassRoom(models.Model):
    teacher = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)

class Student(models.Model):
    name = models.CharField(max_length=128)
    class_room = models.ForeignKey(ClassRoom)

This way you can add as many students as you like. 这样,您可以添加任意多的学生。 This is the standard practice, but if you really want to just save the names and NOTHING else (and are using PostgreSQL), you can also use the ArrayField for that. 这是标准做法,但是如果您真的只想保存名称而没有其他内容(并且正在使用PostgreSQL),则也可以使用ArrayField。 But check it out in the documentation yourself. 但是请自己在文档中查看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM