刚在stackoverflow上问的问题,大神们求救
http://stackoverflow.com/questions/20580815/django-admin-inline-with-abstract-class-and-m2m-field
This problem almost drives me crazy :(
I was trying to use the StackedInline in admin interface.
The code below is in django documentation.
model.py
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
admin.py
class MembershipInline(admin.StackedInline):
model = Membership
extra = 1
class PersonAdmin(admin.ModelAdmin):
inlines = (MembershipInline,)
class GroupAdmin(admin.ModelAdmin):
inlines = (MembershipInline,)
But if the Group is an abstract base class and PublicGroup is subclass inherited from Group. Membership is used to relate PublicGroup and Person.
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='%(class)s_Membership')
class Meta:
abstract = True
class PublicGroup(Group):
pass
class Membership(models.Model):
person = models.ForeignKey(Person)
group = models.ForeignKey(Group)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
after running the command
python manage.py sql test
I got error "AssertionError: ForeignKey cannot define a relation with abstract class Group".
After searching for solution, I know foreign key cannot point to a abstract class. Some solutions recommended to use generic relation. So I change the code again.
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = generic.GenericRelation('Membership')
class Meta:
abstract = True
class PublicGroup(Group):
pass
class Membership(models.Model):
person = models.ForeignKey(Person)
content_type = models.ForieignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
This time the command
python manage.py sql test
returns no error. But I got error when I tried to add data on admin interface. The error says Membership is not a foreign key of PublicGroup. StackedInline still doesn't work.
Now I really don't know what to do. Does anyone know how to achieve this function.
Thanks for reading!