开发者

django many-to-many query outputs <foo: <built-in function id>>

开发者 https://www.devze.com 2023-04-05 16:17 出处:网络
I am using Django 1.3 and sqlite3. My models are: class Trial(models.Model): person = models.ManyToManyField(Person, blank=True)

I am using Django 1.3 and sqlite3. My models are:

class Trial(models.Model):
    person = models.ManyToManyField(Person, blank=True)
    def __unicode__(self):
        return self.strId

class Person(models.Model):
    name = models.CharField(max_length=500)
    def __unicode__(self):
        return self.name

I would like to query the database and return a list of Trial.id entries that contain a person with the name "Tom". My attempt looks like this:

found_entries = Person.objects.filter(name__contains="Tom")
Toms = []
for items in found_entries:
    Toms.append(Trial.objects.filter(person__name__contains="Tom"))

When I send the Toms list to the template I get a list full of <Trial: <built-in function id>>

However, when I try to get Toms.id, or Toms.name, or even Toms.person I get an error:

'QuerySet' object has no attribute 'id'

What I ultimately want is a list of the Trial.id开发者_如何学编程 that contain person's named "Tom". Any help is grately appreciated.


Your initial query is redondant. Why not using this:

# all the trials with a person whom name contains 'Tom'
trials = Trial.objects.filter(person__name__contains='Tom')

And in your template :

{% for trial in trials %}
    {{ trial.id }}
{% endfor %}


class Trial(models.Model):
    person = models.ManyToManyField(Person, blank=True, related_name="user_trials")
    def __unicode__(self):
        return self.strId

in view:

found_entries = Person.objects.filter(name__contains="Tom")

template:

{% for found_entry in found_entries %}
    {% for trial in found_entry.user_trials.all %}
        {{ trial.id }}
    {% endfor %}
{% endfor %}
0

精彩评论

暂无评论...
验证码 换一张
取 消