如果没有
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
这与您排除个人资料的方式有关!当您使用
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))