bottus
bottus

Reputation: 903

how to query in nested foreignKey

The idea is pretty simple, I've got to query several models in my func. In order to keep it clean in my template, I've decided to abstract a new model that would contain my data. I'm creating the model via a lambda.

Here are the models.

class Contact(models.Model):
   created_date = models.DateTimeField(auto_now_add=True)
   updated_date = models.DateTimeField(auto_now=True)
   lastname = models.CharField(max_length=50, null=True, blank=True)
   firstname = models.CharField(max_length=50, null=True, blank=True)
   email = models.EmailField(null=True, blank=True)

class CRecord(models.Model):
   created_date = models.DateTimeField(auto_now_add=True)
   updated_date = models.DateTimeField(auto_now=True)
   place = models.ForeignKey(Place, related_name="record")
   contact = models.ForeignKey(Contact, blank=True, null=True, related_name="records")

class Place(models.Model):
   created_date = models.DateTimeField(auto_now_add=True)
   updated_date = models.DateTimeField(auto_now=True)
   deleted_date = models.DateTimeField(blank=True, null=True)
   name = models.CharField(max_length=100, db_index=True)
   lat = models.FloatField(db_index=True)
   lon = models.FloatField(db_index=True)

Here is my lambda to create my new object:

tr_contact = lambda x: dict(first_name=x.firstname,
                            last_name=x.lastname,
                            owned_place=?)

Basically the ones I wanna get for owned_place are the place contained in CRecord. The part I'm struggling with is the fact that for each contact, there are several record, and in each record, there are several places. the field owned_place should be equal to every place contained in every record.

I've tried a few and even wondered if really it is possible in one request..

Upvotes: 0

Views: 294

Answers (1)

Sayse
Sayse

Reputation: 43320

Jus't don't... what you're doing here is basically recreating values or (values_list).

The difference here is that your approach is resolving an entire query lookup which is more costly than it needs to be, so either use the above...

 my_records_queryset.values('firstname', 'lastname', 'place')

or you may wish to look into Django Rest Framework and serializers which could give you more control on what values you get back for your relational fields.

Upvotes: 1

Related Questions