Django表单覆盖ForeignKey查询集

时间:2014-07-21 15:39:31

标签: django django-models django-forms django-managers

我正在创建一个用于创建未发布的Artist个实例的表单,然后在发布之前将Artwork添加到艺术家。

我有经理隐藏published=False艺术家,但不知道如何绕过ForeignKey

models.py

class PublishedManager(models.Manager):
    """Returns only published Artists in queryset"""
    def get_query_set(self):
        qs = super(VisibleManager, self).get_query_set()
        qs = qs.filter(status='published')
        return qs

class Artist(models.Model):
    objects = PublishedManager() # Used overall on the site to hide published=False objects
    admin_objects = models.Manager() # Default manager Will be used in admin to show invisible     objects too

class Artwork(models.Model):
    artist= models.ForeignKey(Artist)

forms.py

class ArtworkForm(forms.ModelForm):


    def __init__(self,  *args, **kwargs):
        super(ArtworkForm,self).__init(args,kwargs)
        from django.db import models
        self.fields['artist'].queryset = Artist.admin_objects.all()

>>> form=Artwork_form(artist=180) #unpublished artist pk
>>> form.errors

Model artist with pk 180 does not exist

我需要制作表格"请参阅" FK未发表的艺术家,我怎样才能实现这一目标?

谢谢。

1 个答案:

答案 0 :(得分:3)

我找到了解决方案!!!

原始信息在http://www.hoboes.com/Mimsy/hacks/custom-managers-django-foreignkeys/

我实现了CustomManagerForeignKey,因为这篇文章的autor已经写了一个例外(否则在胜利工作中):

用法:

class Artwork(models.Model):
    artist= CustomManagerForeignKey(Artist, manager=Artist.admin_objects)

并在CustomManagerForeignKey

中对此进行了修复
class CustomManagerForeignKey(models.ForeignKey):
    def __init__(self, *args, **kwargs):
        if 'manager' in kwargs:
            self.customManager = kwargs['manager'] #Here i removed the () in the end of the line
            del kwargs['manager']
        else:
            self.customManager = None
        super(CustomManagerForeignKey, self).__init__(*args, **kwargs)