Without to_field, it works. But, setting to_field to name, you can simply type name in the input field of django admin, instead of id.
I am just wondering why the api behaves differently if to_field is set to another field other than id. We create like this: >>> pet = Pet.objects.create(owner=person, name='B') But, we have to get like this: >>> pet = Pet.objects.get(owner=person.name, name='B') Hence, we cannot get_or_create On 8月10日, 上午9时37分, Renne Rocha <rennero...@gmail.com> wrote: > Try defining the pet model like this: > > class Pet(models.Model): > owner = models.ForeignKey(Person) > name = models.CharField(max_length=30) > > Than it will work. > > On Fri, Aug 6, 2010 at 7:25 AM, bhuztez <bhuz...@gmail.com> wrote: > > I have my models declared in this way: > > > class Person(models.Model): > > name = models.CharField(max_length=50, unique=True) > > > class Pet(models.Model): > > owner = models.ForeignKey(Person, to_field='name') > > name = models.CharField(max_length=30) > > > def __unicode__(self): > > return self.name > > > I got empty list when trying to get pets from its owner. > > > >>> person = Person(name='A') > > >>> person.save() > > >>> pet = Pet(owner=person, name='B') > > >>> pet.save() > > >>> Pet.objects.filter(owner=person) > > [] > > >>> Pet.objects.filter(owner__in=Person.objects.all()) > > [] > > > It works as expected with explicit id > > >>> Pet.objects.filter(owner__id=person.id) > > [<Pet: B>] > > > Pet.objects.filter(owner__id__in=Person.objects.all().values_list('id', > > flat=True)) > > [<Pet: B>] > > > Setting owner to the name of the person works also > > >>> Pet.objects.filter(owner=person.name) > > [<Pet: B>] > > > I didn't find any document on this, is this a convention, or this is a > > bug? > > > -- > > You received this message because you are subscribed to the Google Groups > > "Django users" group. > > To post to this group, send email to django-us...@googlegroups.com. > > To unsubscribe from this group, send email to > > django-users+unsubscr...@googlegroups.com<django-users%2bunsubscr...@googlegroups.com> > > . > > For more options, visit this group at > >http://groups.google.com/group/django-users?hl=en. > > -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.