【问题标题】:Relate three models together based on profile field根据 profile 字段关联三个模型
【发布时间】:2018-09-03 20:14:31
【问题描述】:

我希望能够将我的用户模型、配置文件模型和单独的模型关联在一起。我当前的模型结构如下所示:

class Profile(models.Model):
    COORDINATOR = 1
    LEADER = 2
    ADMIN = 3
    ROLE_CHOICES = (
        (COORDINATOR, 'Coordinator'),
        (LEADER, 'Leader'),
        (ADMIN, 'Admin'),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    team = models.ForeignKey(Team, on_delete=models.PROTECT,null=True)
    role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True)
    agent_code = models.CharField(max_length=15, null=True, blank=True)

class DailyReports(models.Model):
    agent_code = models.CharField(max_length=15, blank=True, null=True)
    product = models.CharField(max_length=15)
    num_free = models.IntegerField(blank=True, null=True)
    apps_submitted = models.IntegerField(blank=True, null=True)
    apps_activated = models.IntegerField(blank=True, null=True)
    prem_submitted = models.DecimalField(max_digits=20, decimal_places=2,blank=True, null=True)
    date = models.DateField(auto_now=False,auto_now_add=False,null=True,blank=True)

我可以将ProfileUser 关联起来,但我正在尝试将Profile 关联到agent_code 上的DailyReports,然后关联到User 模型。

所以用类似下面的东西:

    test_query = DailyReports.objects.filter(product__in=['LT15', 'LT121']) \
            .values('agent_code') \
            .annotate(premium=Sum('prem_submitted')) \
            .order_by('-premium') \

我得到了预期的输出:

{'agent_code': 'ABC123', 'premium': Decimal('50015.87')} 
{'agent_code': 'DEF456', 'premium': Decimal('44818.20')} 
{'agent_code': 'GHI789', 'premium': Decimal('35322.35')}
...

但我也想基于agent_codeProfile获取信息,然后根据agent_codeProfileDailyReports之间建立的关系获取相关的User信息,例如我的输出看起来像:

{'agent_code': 'ABC123', 'premium': Decimal('479872.55'), user.profile.first_name, user.profile.last_name, profile.user_id, profile.role} 
{'agent_code': 'DEF456', 'premium': Decimal('448118.20'), user.profile.first_name, user.profile.last_name, profile.user_id, profile.role} 
{'agent_code': 'GHI789', 'premium': Decimal('356322.35'), user.profile.first_name, user.profile.last_name, profile.user_id, profile.role} 

【问题讨论】:

  • 谢谢!不完全确定如何实现它,但我会深入研究文档并尝试在网上找到一些示例。
  • 您是否希望关系具体化,因为 agent_code 似乎是一个字符字段,您需要确保它们是唯一的并且可以在 Profile 模型上使用 agent_code = models.ForeignKey(DailyReports, to_field='agent_code')
  • 它们对于每个Profile 都是唯一的,我猜想与DailyReports 是一对多的关系,因为DailyReports 对象的多个实例具有相同的agent_code。我不知道如何实现它。如果我将Profile.agent_code 设置为PK 并将DailyReports.agent_code 设置为ForeignKey,这是一条可以走的路吗?不确定如何在我的示例中实现 GenericForeignKey()。
  • 我在个人资料中尝试from reports.models import DailyReports 时也收到import error,但from reports.models import * 没有错误。不知道发生了什么。编辑:我相信将其缩小到循环进口。

标签: python django django-models django-select-related


【解决方案1】:

如果一个配置文件将链接到多个 DailyReports,则最佳设置必须是

class Profile(models.Model):
    COORDINATOR = 1
    LEADER = 2
    ADMIN = 3
    ROLE_CHOICES = (
        (COORDINATOR, 'Coordinator'),
        (LEADER, 'Leader'),
        (ADMIN, 'Admin'),
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    team = models.ForeignKey(Team, on_delete=models.PROTECT,null=True)
    role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True)
    # agent_code = models.CharField(max_length=15, null=True, blank=True) # <-- Remove the agent code from the profile model.

DailyReports 与配置文件是多对一的关系。

class DailyReports(models.Model):
    profile = models.ForeignKey('Profile', related_name='daily_reports')
    agent_code = models.CharField(max_length=15, blank=True, null=True)
    product = models.CharField(max_length=15)
    num_free = models.IntegerField(blank=True, null=True)
    apps_submitted = models.IntegerField(blank=True, null=True)
    apps_activated = models.IntegerField(blank=True, null=True)
    prem_submitted = models.DecimalField(max_digits=20, decimal_places=2,blank=True, null=True)
    date = models.DateField(auto_now=False,auto_now_add=False,null=True,blank=True)

获取个人资料的 DailyReports 列表

profile = Profile.objects.prefetch_related('daily_reports').first()

profile.daily_reports.all()

通过档案报告查询

qs = (
    profile.daily_reports.filter(product__in=['LT15', 'LT121'])
        .annotate(premium=Sum('prem_submitted'))
        .values_list('agent_code', 'premium', 'profile__first_name', 'profile__last_name', 'profile__user_id', 'profile__role', named=True)
        .order_by('-premium')
)

results = [
    {
       'agent_code': report.agent_code,
       'premium': report.premium
       'first_name': report.profile__first_name,
       'last_name': report.profile__last_name,
       'user_id': report.profile__user_id,
       'role': report.profile__role
    } for report in qs
]

## {'agent_code': 'ABC123', 'premium': Decimal('479872.55'), ...} 

【讨论】:

    猜你喜欢
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2012-12-24
    相关资源
    最近更新 更多