0

I'm using Django 1.6 with Python 2.7 and I have few related models:

# keys/models.py
class Key(models.Model):
    user = models.ForeignKey('auth.User')
    is_valid = models.BooleanField()

# entities/models.py
class Entity(models.Model):
    user = models.ForeignKey('auth.User')
    key = models.ForeignKey('keys.Key')
    active = models.BooleanField(default=False)

# profile/models.py
class Profile(models.Model):
    user = models.ForeignKey('auth.User')
    profile_id = models.PositiveIntegerField(null=True, blank=True)

Is it possible to make a single-line query which would check these conditions:

  • Key.is_valid must be True
  • Entity.active must be True
  • Profile.profile_id must not be null (or None)

The only thing I can pass to that query is request.user.

errata
  • 5,695
  • 10
  • 54
  • 99

2 Answers2

1

if you are wanting to get Entity objects:

objects = Entity.objects.filter(active=True, 
                                key__is_valid=True, 
                                user__profile__profile_id__isnull=False)
JamesO
  • 25,178
  • 4
  • 40
  • 42
  • You are sure that this last line will work ? Enitity is not connected with Profile, it's connected with auth.User – Silwest Feb 20 '14 at 18:07
  • @Silwestpl, I believe so, enitity may not be connected to profile but user is hence the double join – JamesO Feb 20 '14 at 18:17
  • Yeah, `Entity` is not connected to `Profile`, but I was just testing this, seems like it works fine... Give me few more minutes to test few more cases and I'll probably accept this since it was the first answer :) – errata Feb 20 '14 at 18:22
  • without testing it is *should* work :), the orm can follow multi relations https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships – JamesO Feb 20 '14 at 18:25
  • Ah yes, I was trying to follow that way but obviously had some error somewhere... Ok, I did test it as much as possible and the query returns empty QuerySet if any of conditions is not satisfied which is pretty much what I needed. Thanks a lot! – errata Feb 20 '14 at 18:30
1

I think that this is what you need:

Check entity:

entity = Entity.objects.filter(active=True, key__is_valid=True, user=request.user)

Check Profile

profile = Profile.objects.filter(user=request.user, profile_id__isnull=False)
Silwest
  • 1,620
  • 1
  • 15
  • 29
  • Will upvote this answer for effort ;) Accepted JamesO answer just because he was faster and did it in one line :) Thanks anyways! – errata Feb 20 '14 at 18:33