django:foreignkey链接2个表

8qgya5xd  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(262)

在这些代码行中,在bug表下,有一行代码 Assigned_to = models.ForeignKey(User, on_delete=models.CASCADE) 一共有两个表,第一个是project表,第二个是bug表。如何编辑这行代码并使其只显示项目表中提到的人员的姓名?
我已经试过了,但是如何写下所有相关的名字,并确保第一个表中提到的所有名字都显示在这个表中?

Assigned_to = models.ForeignKey(Project, on_delete=models.CASCADE, 
                                          related_name= ' ' | ' ' | ' ' )

显然,使用 '' | '' 不起作用。
如有任何建议,我们将不胜感激。
另外,由于某些原因,我为inline编写的代码行没有显示出来。提前谢谢!

from django.db import models

# Create your models here.

from django.contrib.auth.models import User, Group
from django.db import models
from django.core.mail import EmailMessage
from django.contrib import admin

# Create your models here.

class Project(models.Model):
   STATUS_CHOICE = (
       ('Project Manager', 'Project Manager'),
       ('Technician', 'Technician'),
       ('Tester', 'Tester')
   )
   STATUS_CHOICE_1 = (
       ('Work Assigned', 'Work Assigned'),
       ('Work in Progress', 'Work in Progress'),
       ('Testing', 'Testing'),
       ('Completed', 'Completed')
   )
   Project_Name = models.CharField(max_length=100)
   Project_Description = models.CharField(max_length=100)
   Admin_Name = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Admin_Name_users+')
   Admin_Mail_ID = models.EmailField(max_length=50)
   Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_1_users+')
   Project_Manager_1_Mail_ID = models.EmailField(max_length=50)
   Project_Manager_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_2_users+', blank=True, null=True)
   Project_Manager_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
   Technician_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_1_users+')
   Technician_1_Mail_ID = models.EmailField(max_length=50)
   Technician_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_2_users+', blank=True, null=True)
   Technician_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
   Technician_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_3_users+', blank=True, null=True)
   Technician_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
   Tester_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Tester_1_users+')
   Tester_1_Mail_ID = models.EmailField(max_length=50, default='Example@gmail.com')
   Additional_User_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
   Additional_User_1_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
   Additional_User_1_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
   Additional_User_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
   Additional_User_2_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
   Additional_User_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
   Additional_User_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
   Additional_User_3_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
   Additional_User_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
   Status_of_the_project = models.CharField(max_length=18, choices=STATUS_CHOICE_1)
   Created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
   Finish_Date = models.DateTimeField(null=True, blank=True)
   Supporting_Documents = models.FileField(null=True, blank=True)

   class FlatPageAdmin(admin.ModelAdmin):
       fieldsets = (
           (None, {
               'fields': ('Project_Name','Project_Description','Admin_Name','Admin_Mail_ID','Project_Manager_1','Project_Manager_1_Mail_ID',
'Technician_1','Technician_1_Mail_ID','Tester_1','Tester_1_Mail_ID','Status_of_the_project','Created','Finish_Date','Supporting_Documents',
)
           }),
           ('Add More Users', {
               'classes': ('collapse',),
               'fields': ('Project_Manager_2','Project_Manager_2_Mail_ID','Technician_2','Technician_2_Mail_ID',
                          'Technician_3','Technician_3_Mail_ID','Additional_User_1','Additional_User_1_Type',
                          'Additional_User_1_Mail_ID','Additional_User_2','Additional_User_2_Type','Additional_User_2_Mail_ID',
                          'Additional_User_3','Additional_User_3_Type','Additional_User_3_Mail_ID'),
           }),
       )

   def __str__(self):
       return self.Project_Name

   class Meta:
       verbose_name_plural = "List Of Projects"

class Bug(models.Model):

   STATUS_CHOICE = (
       ('Unassigned', 'Unassigned'),
       ('Assigned', 'Assigned'),
       ('Testing', 'Testing'),
       ('Tested', 'tested'),
       ('Fixed', 'Fixed')
   )
   STATUS_CHOICE_1 = (
       ('Bug', 'Bug'),
       ('Issue', 'Issue'),
       ('Enhancement', 'Enhancement'),
       ('Not an issue or bug', 'Not an issue or bug'),
       ('Fixed', 'Fixed')
   )
   Project = models.ForeignKey(Project, on_delete=models.CASCADE)
   Issue_Title = models.CharField(max_length=50, blank=True, null=True)
   Situation_Type = models.CharField(max_length=25, choices=STATUS_CHOICE_1)
   Basic_Description = models.CharField(max_length=100)
   Detailed_Description = models.TextField(default='The Description, here.')
   Status = models.CharField(max_length=18, choices=STATUS_CHOICE)
   Assigned_to = models.ForeignKey(User, on_delete=models.CASCADE)
   Assigned_to_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
   Admin_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
   Reported_by = models.CharField(max_length=50, blank=True, null=True)
   Reporters_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
   Reported_Date = models.DateTimeField(null=True, blank=True)
   Created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
   Updated = models.DateTimeField(auto_now=True, null=True, blank=True)
   Deadline_Date = models.DateTimeField(null=True, blank=True)
   Supporting_Documents_By_Reporter = models.FileField(null=True, blank=True)
   Project_Managers_Comment = models.TextField(default='The Description, here.')
   Supporting_Documents_by_Project_Manager = models.FileField(null=True, blank=True)
   Technicians_Comment = models.TextField(default='The Description, here.')
   Supporting_Documents_by_Technician = models.FileField(null=True, blank=True)
   Testers_Comment = models.TextField(default='The Description, here.')
   Supporting_Documents_by_Tester = models.FileField(null=True, blank=True)

   def __str__(self):
       return '{} ({})  [{}]'.format(self.Project, self.Situation_Type, self.Status, self.Issue_Title)

   def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
       if self.id:
           user=self.Assigned_to
           self.Assigned_to_Mail_ID=user.email
       send_mail(self.Admin_Mail_ID, ass=self.Assigned_to_Mail_ID)
       super(Bug, self).save()

   class Meta:
       verbose_name_plural = "Projects Tasks/Issues"

def send_mail(admin,ass):
    email=EmailMessage('Changes made to Task','Changes have been made to one of your Task reports and we hereby request you to have a look at it at the earliest.', to=[admin,ass])
    email.send()
gkn4icbw

gkn4icbw1#

@flyingteller试图引用以下声明。如果您想创建外键关系,您需要添加另一个字段,就像我为channelsubscription类的字段subscribed\u channel添加的那样,使用channel class字段subscribed\u channels\u列表

class Channel(models.Model):
  channel_id = models.CharField(max_length = 200, blank = False, primary_key = True)
channel_name = models.CharField(max_length = 200)
channel_value = models.IntegerField(blank = False)
timestamp = models.DateTimeField(
  default = timezone.now)
subscribed_channels_list = models.ManyToManyField(
  'self',
  through = 'ChannelSubscription', #related_name = 'subscribed_channels',
  symmetrical = False
)

class Meta:
  db_table = 'channel'
managed = False

class ChannelSubscription(models.Model):
  channel = models.ForeignKey(Channel, on_delete = models.PROTECT, db_column = 'channel_id', related_name = 'source_channel')
slot = models.ForeignKey(Slot, on_delete = models.PROTECT, db_column = 'slot_id')
subscribed_channel = models.ForeignKey(Channel, on_delete = models.PROTECT, db_column = 'subscribed_channel_id', related_name = 'subscribed_channel')
is_active = models.CharField(max_length = 200)
timestamp = models.DateTimeField(
  default = timezone.now)

class Meta:
  db_table = 'channel_subscription'
managed = False
vojdkbi0

vojdkbi02#

以下几点对您有很大帮助:
在代码中使用pep8。例如,字段名应该全部小写,如下面的示例代码所示。
了解数据库规范化。在数据库中,您几乎不应该看到编号字段(即:additional\u user\u 1、additional\u user\u 2、additional\u user\u 3)。理想情况下,这些应该移动到一个单独的模型。
不知道你为什么要到处使用状态选择和状态选择1。将它们恰当地命名为它们的实际名称。
你的名字太冗长了,好像有点搞不清楚。请看一下我如何在下面的示例代码中使用这些名称。如果你有任何问题,请告诉我。
我假设每个项目只有一个管理员,每个人只担任一个角色(例如,如果一个人是技术人员,他/她永远都是技术人员)。如果这些假设不正确,您可能需要调整下面的代码。
在下面的示例中,我为与项目相关联的各种人员创建了一个与用户具有onetoone关系的person模型。项目有很多关系(即:每个人可以属于多个项目,每个项目可以有多个人)。最后,在bug模型上分配给的是一个foreignkey to person(多个bug可以分配给一个人)。
要向项目中添加更多人员,只需使用字段集。
这只是一个开始。我会为诸如注解和文档之类的东西添加额外的模型,以便您可以从项目经理那里获得多个注解或文档。

from django.db import models

# Create your models here.

from django.contrib.auth.models import User, Group
from django.db import models
from django.core.mail import EmailMessage
from django.contrib import admin

# Create your models here.

class Project(models.Model):
    STATUS_CHOICE = (
       ('Work Assigned', 'Work Assigned'),
       ('Work in Progress', 'Work in Progress'),
       ('Testing', 'Testing'),
       ('Completed', 'Completed')
    )
    project_name = models.CharField(max_length=100)
    project_description = models.CharField(max_length=100)
    status_of_the_project = models.CharField(max_length=18, choices=STATUS_CHOICE)
    created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    finish_date = models.DateTimeField(null=True, blank=True)
    supporting_documents = models.FileField(null=True, blank=True)
    admin = models.ForeignKey(Person, on_delete=models.CASCADE)

    class FlatPageAdmin(admin.ModelAdmin):
        fieldsets = (
            (None, {
                'fields': ('project_name','project_description','status_of_the_project','created','finish_date','supporting_documents',)
            })
        )

   def __str__(self):
       return self.Project_Name

   class Meta:
       verbose_name = "Project"
       verbose_name_plural = "Projects"

class Person(models.Model):
    PERSON_TYPE = (
        ('Admin', 'Admin'),
        ('Project Manager', 'Project Manager'),
        ('Technician', 'Technician'),
        ('Tester', 'Tester')
    )

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_person')
    projects = models.ManyToManyField(Project, null=True, related_name='people')
    mail_id = models.EmailField(max_length=50, blank=True, null=True)
    person_type = models.CharField(max_length=18, choices=PERSON_TYPE)

    class Meta:
        verbose_name = "Person"
        verbose_name_plural = "People"

class Bug(models.Model):
    STATUS_CHOICE = (
        ('Unassigned', 'Unassigned'),
        ('Assigned', 'Assigned'),
        ('Testing', 'Testing'),
        ('Tested', 'tested'),
        ('Fixed', 'Fixed')
    )
    SITUATION_TYPE = (
        ('Bug', 'Bug'),
        ('Issue', 'Issue'),
        ('Enhancement', 'Enhancement'),
        ('Not an issue or bug', 'Not an issue or bug'),
        ('Fixed', 'Fixed')
    )

    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    issue_title = models.CharField(max_length=50, blank=True, null=True)
    situation_type = models.CharField(max_length=25, choices=SITUATION_TYPE)
    basic_description = models.CharField(max_length=100)
    detailed_description = models.TextField(default='The Description, here.')
    status = models.CharField(max_length=18, choices=STATUS_CHOICE)
    assigned_to = models.ForeignKey(Person, on_delete=models.CASCADE)
    # assigned_to_mail_ID - this can be pulled from the assigned_to relationship
    # Admin name and ID can be pulled from the project->people relationship
    reported_by = models.CharField(max_length=50, blank=True, null=True)
    reporters_mail_id = models.EmailField(max_length=50, blank=True, null=True)
    reported_date = models.DateTimeField(null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    updated = models.DateTimeField(auto_now=True, null=True, blank=True)
    deadline_date = models.DateTimeField(null=True, blank=True)
    supporting_documents_by_reporter = models.FileField(null=True, blank=True)
    project_managers_comment = models.TextField(default='The Description, here.')
    supporting_documents_by_project_manager = models.FileField(null=True, blank=True)
    technicians_comment = models.TextField(default='The Description, here.')
    supporting_documents_by_technician = models.FileField(null=True, blank=True)
    testers_comment = models.TextField(default='The Description, here.')
    supporting_documents_by_tester = models.FileField(null=True, blank=True)

    def __str__(self):
       return '{} ({})  [{} {}]'.format(self.project, self.situation_type, self.status, self.issue_title)

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        if self.id:
           user=self.assigned_to.user
           self.assigned_to.mail_id=user.email
        send_mail(self.project.admin.mail_id, ass=self.assigned_to.mail_id)
        super(Bug, self).save()

    class Meta:
        verbose_name = "Project Task/Issue"
        verbose_name_plural = "Project Tasks/Issues"

def send_mail(admin, ass):
    email=EmailMessage('Changes made to Task','Changes have been made to one of your Task reports and we hereby request you to have a look at it at the earliest.', to=[admin, ass])
    email.send()

相关问题