Django - 过滤对象(同一模型的多个类别)

时间:2017-01-30 22:29:08

标签: django

我的Site.model包含category,category1值: 网站A:   - category1   - 类别2 网站B:   - category1   - category3

我想过滤特定类别中的对象以仅显示相关网站(例如,在类别1中应该有网站A和网站B,在类别3中 - 仅显示网站B)。现在我的代码看起来像:

<div id="a">
  Lorem, (ipsum, dolor, sit), amet, consectetur, adipiscing, elit
  </div><br>
<input type="button" value="Change" onclick="change()" />
<script>
  function change(){
     var str = document.getElementById('a').innerHTML;
        var arr = str.split(',');
        var index;
        var paranthess;
        for (var i = 0; i < arr.length; i++)
        {
            if (arr[i].indexOf('(') > 0)
            {
                arr[i] += '-foo';
                for (var j = i + 1; j < arr.length; j++)
                {
                    if (arr[j].indexOf(')') == -1)
                        arr[j] += "-foo";
                    else
                    {
                        var last = arr[j];
                        arr[j] = [arr[j].slice(0, arr[j].length - 1), "-foo", arr[j].slice(arr[j].length - 1)].join('');
                        break;
                    }
                }

            }
        }
        
        alert(arr.join());
    }
  </script>

是否可以写出类似??:

的内容
class SiteList():

    def __init__(self, category_slug, subcategory_slug=None):
        self.cat_slug = category_slug
        self.subcat_slug = subcategory_slug

    def get_context(self):
        context = {}
        if self.subcat_slug is None:
            category = Category.objects.get(slug=self.cat_slug)
            sites = Site.objects.filter(category=category, is_active=True)
            subcategory = SubCategory.objects.values().filter(category=category)
        else:
            category = Category.objects.get(slug=self.cat_slug)
            subcategory = SubCategory.objects.filter(category=category
                                                     ).get(slug=self.subcat_slug)
            sites = Site.objects.filter(subcategory=subcategory, is_active=True)
        context['subcategory'] = subcategory
        print(subcategory)
        context['category'] = category
        context['sites'] = sites
        return context

我不知道如何过滤网站以显示正确的对象。

这是我的网站型号:

sites = Site.objects.filter(category=category or category1=category, is_active=True)

和我的分类视图:

class Site(models.Model):
    category = models.ForeignKey('Category')
    subcategory = ChainedForeignKey(
        'SubCategory',
        chained_field='category',
        chained_model_field='category',
        show_all=False,
        auto_choose=True)
    name = models.CharField(max_length=70)
    description = models.TextField()

    keywords = MyTextField()
    date = models.DateTimeField(default=datetime.now, editable=False)
    url = models.URLField()
    is_active = models.BooleanField(default=False)

    category1 = models.ForeignKey('Category', related_name='category', blank=True, null=True)
    subcategory1 = ChainedForeignKey(
        'SubCategory',
        chained_field='category1',
        chained_model_field='category',
        related_name='subcategory',
        show_all=False,
        auto_choose=True, blank=True, null=True)

    group = models.CharField(max_length=10, choices=(('podstawowy', 'podstawowy'),
                                                     ('premium', 'premium')), default='podstawowy')

    def get_absolute_url(self):
        return reverse('site', args=[str(self.category.slug),
                                     str(self.subcategory.slug), str(self.id)])

    def get_thumb(self):
        host = urlparse(self.url).hostname
        if host.startswith('www.'):
            host = host[4:]
        thumb = 'http://free4.pagepeeker.com/v2/thumbs.php?size=s&url=' + host
        return thumb

    class Meta:
        verbose_name_plural = "Strony"

    def __str__(self):
        return self.name

感谢您提供任何线索。

1 个答案:

答案 0 :(得分:1)

  

是否可以写出类似??:

的内容
   sites = Site.objects.filter(category=category or category1=category, is_active=True)

是的,如果您想使用or

,请使用Q对象
  

如果您需要执行更复杂的查询(例如,使用 OR 语句进行查询),则可以使用 Q 对象。< / p>      

Q 对象( django.db.models.Q )是用于封装关键字参数集合的对象。这些关键字参数在上面的“字段查找”中指定。

from django.db.models import Q
sites = Site.objects.filter(
    Q(category=category) | Q(category1=category), 
    is_active=True)