2017-05-29 455 views
0

問題

一個ManyToManyField我有兩個多對多字段(disciplinessubjects)顯示Excerpt模式,我想在管理頁面只顯示subjectsdisciplines該corresponde。過濾器在Django管理頁面

DISCIPLINE | SUBJECT 
portugues | article 
portugues | verbs 
portugues | nons 
math  | numbers 
math  | equations 

DISCIPLINE = math 

DISCIPLINE | SUBJECT 
math  | numbers 
math  | equations 

我如何可以部分地解決

對於我使用的功能formfield_for_manytomany內部管理,它可以很好地用於過濾的對象,但我無法弄清楚如何篩選根據選用的disciplinesubject對象,

我試過

我嘗試使用本功能離子in model.py get_disciplines返回相應的id,然後過濾主題,但這種方法似乎並不適用於我的管理代理模型,因爲引發錯誤global name 'get_disciplines' is not defined可能因爲我可以訪問model.py之外。我也試過在管理代理中聲明這個方法,但也不起作用。

我的代碼

# model.py 
class Discipline(models.Model): 
    id = models.CharField(max_length=15, primary_key=True) 
    name = models.CharField(max_length=100) 

class Subject(models.Model): 
    id = models.CharField(max_length=15, primary_key=True) 
    name = models.CharField(max_length=100) 
    disciplines = models.ManyToManyField(Discipline) 

class Excerpt(models.Model): 
    discipline = models.ManyToManyField(Discipline) 
    subjects = models.ManyToManyField(Subject) 

    # my idea 
    def get_disciplines(self): 
     e = self.discipline.first() 
     return e.id 

# admin.py 
class ExcerptTaggerAdmin(ImageCroppingMixin, admin.ModelAdmin): 
    filter_horizontal = ('subjects','discipline') 

    def formfield_for_manytomany(self, db_field, request, **kwargs): 
     if db_field.name == "subjects": 
      kwargs["queryset"] = Subject.objects.filter(disciplines = get_discipline) 
     return super(ExcerptTaggerAdmin, self).formfield_for_manytomany(db_field, request, **kwargs) 

class ExcerptTagger(Excerpt): 
    class Meta: 
     proxy = True 

我不是一個職業在Django,所以我覺得可以很簡單的人,有更多的經驗,我希望你能幫助我

回答

0

我發現了一個解決方案,但它不是那麼好,但它的工作

def formfield_for_manytomany(self, db_field, request, **kwargs): 
    if db_field.name == "subjects": 
     self_pub_id = request.resolver_match.args[0] 

     d = Excerpt.objects.get(id=self_pub_id).discipline.first() 

     kwargs["queryset"] = Subject.objects.filter(disciplines=d) 

    return super(ExcerptTaggerAdmin, self).formfield_for_manytomany(db_field, request, **kwargs) 

如果有人有更好的解決方案,我將不勝感激