Django 使用“Profile”的两个外键动态访问“Friend”模型
我创建了一个朋友模型,它由两个概要文件模型实例组成。之所以使用单独的模型,首先是因为朋友模型具有与朋友关系相关的特殊属性 在这个朋友模型中,我还跟踪关系的请求者和接受者,因为这对我的站点非常重要。这要求我为每个关系都有一个单独的字段,并且它们是概要文件模型的FKs。以下是两个模型:Django 使用“Profile”的两个外键动态访问“Friend”模型,django,django-models,django-templates,django-views,Django,Django Models,Django Templates,Django Views,我创建了一个朋友模型,它由两个概要文件模型实例组成。之所以使用单独的模型,首先是因为朋友模型具有与朋友关系相关的特殊属性 在这个朋友模型中,我还跟踪关系的请求者和接受者,因为这对我的站点非常重要。这要求我为每个关系都有一个单独的字段,并且它们是概要文件模型的FKs。以下是两个模型: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,
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)
使用这种结构,在我想要检索单个概要文件参与的所有好友实例的实例中,我需要进行两个查询:一个是针对他是请求者的实例,另一个是针对概要文件是接受者的实例。这两个查询集的组合为我提供了个人资料所属的所有朋友关系的总列表——我在制作邮件收件箱之类的东西时需要这个总列表
尝试创建消息列表视图时,我创建了如下视图:
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))
{% for friend in friend_list %}
{{friend.requester_asks}} <br />
{% endfor %}
这样做的问题是,虽然它允许我在模板中访问朋友对象属性,但我似乎找不到一种方便的方法来检索属于朋友关系的其他参与者的必要配置文件属性
因此,在模板中,我可能有如下内容:
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))
{% for friend in friend_list %}
{{friend.requester_asks}} <br />
{% endfor %}
我可以访问好友模型的属性,但如何访问其他好友的配置文件对象属性,如Profile\u picture?
单个用户既可以是请求者,也可以是接受者,这使得访问概要文件模型属性的能力变得复杂
提前谢谢
编辑:我意识到这可能需要对模型关系进行重大更改。我愿意接受任何建议 我将利用您正在评估视图中的查询集这一事实,使用指向不是原始用户的FK的属性对它们进行注释
for friend in as_requester_list:
friend.other_friend = friend.accepter
for friend in as_accepter_list:
friend.other_friend = friend.requester
现在,您可以在模板中遍历friend_列表,并访问
{{ friend.other_friend.profile_picture }}
诸如此类。您能建议查找什么以进一步了解此注释以及如何将其传递到模板中吗?我不知道这是可能的,我甚至不确定这是python还是django特有的。我不确定你在问什么。这只是将另一个属性添加到列表中的每个实例。