我正在创建一个用于创建未发布的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未发表的艺术家,我怎样才能实现这一目标?
谢谢。
答案 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)