Saturday, 28 May 2022

Non FK models tied together by ID (unmanaged model) - how to filter in Django?

I have two models that are related - but they are not a FK relationship in Django because one is a non-managed model with the data coming from a pre-populated DB table.

class Enrollment(models.Model):
    # This comes from a 'shared app' that is used in other projects 
    id = models.IntegerField(db_column="ID", primary_key=True)
    location_id = models.IntegerField(db_column="locationID")
    grade = models.CharField(db_column="grade", max_length=10)

    class Meta(object):
        managed = False
        db_table = "mytable_Enrollments"

class Location(models.Model):
    # This model exists in an app in the specific project I am working on
    name = models.CharField(max_length=50)
    alternate_name = models.IntegerField()

I'm trying to filter Enrollment models using a list of Location models - but they are not tied together in a FK relationship.

I am trying to get enrollments for a particular location like this:

# This does not work properly because it is returning an empty Queryset when it should have results - but does not hit the db which is what I want
location_ids = Location.objects.filter(id=1).values_list("id", flat=True)
enrollments = Enrollment.objects.filter(location_id__in=location_ids)

The above code returns an empty queryset.

If I cast location_ids to a list (like this: list(location_ids)) and then filter on that, it works.

# This works properly - but hits the db which is NOT what I want
location_ids = Location.objects.filter(id=1).values_list("id", flat=True)
enrollments = Enrollment.objects.filter(location_id__in=list(location_ids))

Is there a way to use the Django ORM to get what I want in this case without causing it to evaluate the queryset?

Additionally, I have tried just returning values instead of values_list but it also returns an empty Queryset when it should not.

# This returns empty queryset
location_ids = Location.objects.filter(id=1).values("id")
enrollments = Enrollment.objects.filter(location_id__in=location_ids)


from Non FK models tied together by ID (unmanaged model) - how to filter in Django?

No comments:

Post a Comment