0

I have the following model with tables related through a Many-to-One Relationship.

class Reading(models.Model):
    reading = models.AutoField(primary_key=True)
    client_connection = models.ForeignKey(ClientConnection, models.DO_NOTHING, db_column='client_connection', blank=True, null=True)
    consumption = models.ForeignKey(Consumption, models.DO_NOTHING, db_column='consumption', blank=True, null=True)
    date = models.DateField(blank=True, null=True)

class Client(models.Model):
    client = models.AutoField(primary_key=True)
    zone = models.ForeignKey('Zone', models.DO_NOTHING, db_column='zone', blank=True, null=True)
    code = models.CharField(unique=True, max_length=255, blank=True, null=True)
    order = models.IntegerField(blank=True, null=True)
    full_name = models.CharField(max_length=255, blank=True, null=True)

class Zone(models.Model):
    zone = models.AutoField(primary_key=True)
    description = models.CharField(max_length=255, blank=True, null=True)
    code = models.CharField(unique=True, max_length=255, blank=True, null=True)

Using Django ORM's select_related() I can create a QuerySet that will follow the foreign-key relationship selecting additional related-objects as follows.

def client_meters(request):
    query = Reading.objects.filter(date__gte=datetime.date(2018,10,31)).select_related('client_connection__client__zone').all()
    c_c = query.client_connection

However, I get the error

c_c = query.client_connection
AttributeError: 'QuerySet' object has no attribute 'client_connection'

What am I missing.

1
  • This doesn't have anything to do with joins. Commented Dec 19, 2018 at 16:59

1 Answer 1

3

That's because you are trying to access client_connection attribute of model instance on model queryset.

This will do:

for obj in query:
    c_c = obj.client_connection
    # do what you want

In simple terms: you are trying to access attribute of list of elements instead of single element.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.