Django:如何过滤掉子元素

时间:2012-07-27 11:25:35

标签: django django-queryset

这是我的模特:

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __unicode__(self):
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    published = models.BooleanField()

    def __unicode__(self):
        return self.headline

有一个外部函数,我没有访问它基本上执行以下操作:

def printBlogs(blogs):
    for blog in blogs:
        print blog.name
        for entry in blog.entry_set.all():
            print " *",entry.headline,":", entry.published

以下代码

from weblogs.models import Blog, Entry
r = Blog.objects.all()
printBlogs(r)

产生

 Blog1
  * Article 1 : True
  * Article 2 : True
  * Article 3 : False
 Blog2
  * Article 1 : True
  * Article 2 : False
  * Article 3 : False

获得以下结果的正确代码是什么(请记住我无权访问printBlogs)

 Blog1
  * Article 1 : True
  * Article 2 : True
 Blog2
  * Article 1 : True

3 个答案:

答案 0 :(得分:0)

for o in queryset:
    if not results.has_key(o.name):
       results[o.name] = list()
    if not (...check if Z):
       results[o.name].append(o)

for a in results:
    print a
    for b in results[a]:
        print b.state

假设你有模特:

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    def __unicode__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()

    def __unicode__(self):
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateTimeField()
    mod_date = models.DateTimeField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()

    def __unicode__(self):
        return self.headline

并且您要排除所有名称为“test”的博客

您将运行代码:

Entry.objects.exclude(的博客 __名= '试验')

它会写查询:

SELECT ... FROM `entry` INNER JOIN `blog` ON (`entry`.`blog_id` = `blog`.`id`) WHERE NOT (`blog`.`name` = test )

答案 1 :(得分:0)

aobjs = [b.a for b in B.objects.exclude(state='Z')]

aobj.b_set.exclude(state='Z')

答案 2 :(得分:0)

使用Blog.objects.all()

更改Blog.objects.filter(entry__published=True)

这应该可以做到!