Reputation: 61
I have two models with 1-1 relationship, User and deviceInfo. I am trying to query to get all Users with a specific device ID, and also only guests.
My Models:
class User(models.Model):
userID = models.CharField(max_length=101,primary_key=True)
guest = models.BooleanField()
class deviceInfo(models.Model):
user = models.ForeignKey(to=User, on_delete=models.CASCADE, unique = True)
deviceID = models.CharField(max_length=101, default=None)
So far I figured out how to filter by device ID. But im not sure how i'd filter this further because the guest value is in another model.
What I have so far: (only filters device id)
numIDs = deviceInfo.objects.filter(deviceID=deviceId).count()
What I tried: (doesn't work)
User.objects.filter(deviceInfo = numID)
I get the error "The QuerySet value for an exact lookup must be limited to one result using slicing."
Upvotes: 1
Views: 1499
Reputation: 5854
Try this one:
User.objects.filter(guest=True, deviceinfo__deviceID=deviceId)
or if you need only user IDs
user_ids = deviceInfo.objects.filter(deviceId=deviceId, user__guest=True).values_list("user", flat=True)
User.objects.filter(id__in=user_ids)
See Django: Lookups that span relationships
Upvotes: 2