how can I filter related (foreign key) objects?

3,333 views
Skip to first unread message

serek

unread,
Feb 16, 2011, 5:51:05 PM2/16/11
to Django users
Hi

I have not idea how to describe my problem, so I show pice of code:


class Aaa(models.Model):
name = models.CharField(max_length=200, unique=True)
is_active = models.BooleanField()

class Meta:
ordering = ('name',)

def doMagic(self):
date = '2010-05-04'
//here I need to take 10 conencted Bbb objects whcich data is less
then date
previous10days = self.bbb_set.filter(Bbb.date <
date).order_by('data')


class Bbb(models.Model):
date = models.DateField()
value = models.DecimalField(max_digits=7, decimal_places=2)
aaa = models.ForeignKey(Aaa)

a = Aaa()
a.doMagic throw error that Bbb.date is undefined - what can be wrong?

Matias Aguirre

unread,
Feb 16, 2011, 6:03:00 PM2/16/11
to django-users
Just refer to the field name, you don't need the class:

prev = self.bbb_set.filter(date__lt=date)

Take a look to field lookup rules:
http://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups-intro

Excerpts from serek's message of Wed Feb 16 20:51:05 -0200 2011:

--
Matías Aguirre <matias...@gmail.com>

Chris Matthews

unread,
Feb 17, 2011, 12:51:48 AM2/17/11
to django...@googlegroups.com

Hi Serek,

 

Try this

    def doMagic(self):

        date = '2010-05-04'

        #//here I need to take 10 conencted Bbb objects whcich data is less then date

        previous10days = Bbb.objects.filter(date__lt=date).order_by('data')

 

Also read up about managers http://docs.djangoproject.com/en/1.2/topics/db/managers/ in case you should consider using it (depending upon how much magic is required from your function).

 

Regards

Chris

--

You received this message because you are subscribed to the Google Groups "Django users" group.

To post to this group, send email to django...@googlegroups.com.

To unsubscribe from this group, send email to django-users...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

 

Reply all
Reply to author
Forward
0 new messages