【问题标题】:Django: ForeignKey linking 2 tablesDjango:ForeignKey 链接 2 个表
【发布时间】:2019-02-21 07:52:32
【问题描述】:

在这些代码行中,在 Bugs 表下,有一行代码显示

Assigned_to = models.ForeignKey(User, on_delete=models.CASCADE)

一共有2个表,第一个是Project表,第二个是Bugs表。如何编辑这行代码并使其仅显示 Project 表中提到的人的姓名?

我已经尝试过了,但是如何写下所有相关名称并确保第一个表中提到的所有名称都显示在此表上?

 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()

【问题讨论】:

    标签: python mysql django django-models


    【解决方案1】:

    对你有很大帮助的几件事:

    • 在您的代码中使用PEP8。例如,您的字段名称 应该全部小写,如下面的示例代码所示。
    • 了解database normalization。你应该几乎从不 请参阅编号字段(即:Additional_User_1、Additional_User_2、 Additional_User_3) 在数据库中。理想情况下,这些应移动到 单独的模型。
    • 不知道您为什么到处使用 STATUS_CHOICE 和 STATUS_CHOICE_1。根据实际情况适当地命名它们。
    • 您似乎对冗长的名称有些困惑。请看看我是如何在下面的示例代码中使用这些名称的。如果您有任何问题,请告诉我。

    我假设每个项目只有一个管理员,并且每个人只担任某个角色(例如,如果一个人是技术员,那么他/她永远只是技术员)。如果这些假设不正确,您可能需要调整以下代码。

    在下面的示例中,我为与项目相关的各种人员创建了一个与 User 具有 OneToOne 关系的 Person 模型。与Project有ManyToMany关系(IE:每个人可以属于多个项目,每个项目可以有多个人)。最后,Bug 模型上的assigned_to 是 Person 的 ForeignKey(可以将多个 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()
    

    【讨论】:

      【解决方案2】:

      @FlyingTeller 尝试参考以下声明。 如果要创建外键关系,则需要像我为 ChannelSubscription 类的字段 subscribed_channel 添加另一个字段,其中 Channel 类字段 subscribed_channels_list

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-15
        • 2012-04-27
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-21
        相关资源
        最近更新 更多