In Django 1.11, I have a model Friend
, and a proxy model Relative
:
class FriendManager(models.Manager):
def get_queryset(self):
return super(RelativeManager, self).get_queryset().filter(is_relative=False)
class Friend(models.Model):
# Model fields defined here
objects = FriendManager()
class RelativeManager(models.Manager):
def get_queryset(self):
return super(RelativeManager, self).get_queryset().filter(is_relative=True)
class Relative(Friend):
class Meta:
proxy = True
objects = RelativeManager()
def save(self, *args, **kwargs):
self.is_relative = True
super(Relative, self).save(*args, **kwargs)
I also have a model FriendPortrait
, which has a foreign key field friend
:
class FriendPortrait(models.Model):
friend = models.ForeignKey(Friend)
And a proxy on that:
class RelativePortrait(FriendPortrait):
class Meta:
proxy = True
Now, I want the detail view for RelativePortraits to only show relatives in the drop-down for friend
.
admin.py:
@admin.register(RelativePortrait)
class RelativePortraitAdmin(admin.ModelAdmin):
fields = ('friend')
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'friend':
kwargs['queryset'] = Relative.objects.all()
return super(RelativePortraitAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
This works, in that only relatives are displayed in the friend
drop-down. However, when I try to save a portrait, Django admin gives me a validation error:
friend instance with id 14 does not exist.
How can I specify that I want to use a proxy model for my foreign key in the RelativePortraitAdmin
?
The problem here is that your ForeignKey
points to the Friend
model. The model's default manager filters out all relatives, so this will not work.
A simple way to solve this would be to restructure your models a bit. Introducing something like a generic Person
model and having Friend
and Relative
inherit from it with proxy=True
. The Person
model shouldn't have a manager that pre-filters the instances; then you could have your ForeignKey
point to person.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.