无法在 django 中排除外键

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

如果没有

Profiles
,我就无法获得
Interaction
。有人看出我做错了什么吗?

#models.py
class Profile(models.Model):
    username = models.CharField(max_length=100)
    
class Interaction(models.Model):
    user_id = models.ForeignKey(Profile,on_delete=models.CASCADE, null=True, blank=True)
#test.py
class TestQueries(TestCase):
    def test_get_profiles_without_interaction(self):
        profile_with_interaction = Profile.objects.get(username='foobar')
        interactions_from_profile = Interaction.objects.filter(
            user_id=profile_with_interaction)
        assert interactions_from_profile
        
        #####FAILS#####
        all_profiles_without_interaction = Profile.objects.exclude(
            pk__in=Interaction.objects.all())
        assert profile_with_interaction not in all_profiles_without_interaction
django django-queryset
1个回答
0
投票

这与您排除个人资料的方式有关!当您使用

pk__in=Interaction.objects.all()
时,应该是
pk__in=Interaction.objects.values_list('user_id', flat=True)

因此,现在您只需排除实际上具有与其链接的交互的个人资料。

all_profiles_without_interaction = Profile.objects.exclude(
    pk__in=Interaction.objects.values_list('user_id', flat=True))
© www.soinside.com 2019 - 2024. All rights reserved.