使用两个外键动态访问“朋友”模型到“个人资料”

问题描述 投票:0回答:1

我创建了一个由两个Friend模型实例组成的Profile模型。首先是单独模型的原因是由于Friend模型具有与“朋友”关系相关的特殊属性。

在这个Friend模型中,我也跟踪关系的requesteraccepter,因为它对我的网站很重要 - 这要求我为这些中的每一个都有一个单独的字段,并且它们是Profile模型的FK。以下是两种型号:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                null=True, blank=True)  
    profile_picture = models.ImageField(
        upload_to=profile_photo_upload_loc,
        blank=True,
        null=True,
        created = models.DateTimeField(auto_now_add=True)


class Friend(models.Model):
    requester = models.ForeignKey(Profile, related_name='is_requester')
    accepter = models.ForeignKey(Profile, related_name='is_accepter')
    requester_asks = models.CharField(max_length=60, null=True)
    accepter_asks = models.CharField(max_length=60, null=True)   

有了这个结构,在我想要检索单个Friend参与的所有Profile实例的情况下,我需要进行两个查询:一个用于那些他是requester而另一个用于那些用于配置文件的人。 accepter。这两个查询集的组合给了我Friend所属的所有Profile关系的总列表 - 在制作消息收件箱时我需要这个总列表。

试图创建一个消息ListView,我做了一个这样的视图:

class MessageListView(ListView):
    template_name = 'chat/listview.html'
    context_object_name = 'friend_list'

    def get_queryset(self, *args, **kwargs):
        profile = Profile.objects.get(user__username=self.request.user)
        as_requester_list = Friend.objects.filter(requester=profile)
        as_accepter_list = Friend.objects.filter(accepter=profile)
        return list(chain(as_accepter_list, as_requester_list))  

这个问题是,虽然它允许我在模板中达到Friend对象属性,但我似乎无法找到一种方便的方法来检索属于朋友关系的另一个参与者的必要的Profile属性。

所以在模板中,我可能会有这样的事情:

{% for friend in friend_list %}

    {{friend.requester_asks}} <br />  

{% endfor %}

我能够访问Friend模型的属性,但如何访问其他朋友(Profile对象)属性,如profile_picture? 单个用户可以是requesteraccepter的事实使得访问Profile模型属性的能力变得复杂。

提前致谢。

编辑:我意识到这可能需要对模型关系进行重大改变。我对任何建议持开放态度。

django django-models django-templates django-views
1个回答
1
投票

我将利用这样一个事实,即您正在评估视图中的查询集,以使用指向不是原始用户的FK的属性来注释它们。

for friend in as_requester_list:
    friend.other_friend = friend.accepter
for friend in as_accepter_list:
    friend.other_friend = friend.requester

现在,您可以遍历模板中的friend_list并进行访问

{{ friend.other_friend.profile_picture }}

等等。

© www.soinside.com 2019 - 2024. All rights reserved.