Reputation: 2356
I'm using the django admin feature as the backend administration for my site. It seems to work perfectly, out of the box for my needs, except for one thing. One of my models has a many-to-many relationship with a User. Here is the model:
class Facility(models.Model):
id = models.IntegerField(primary_key=True)
name = models.TextField()
users = models.ManyToManyField(User)
def __str__(self):
return str(self.id)
I've gotten it to let me add users to the facility on the facility page, but since the Admin form is built in, I don't know how to modify it. I found something that looked like what I want on SO:
admin.site.unregister(User)
class MyUserAdmin(UserAdmin):
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'email', 'password1', 'password2')}
),
)
admin.site.register(User, MyUserAdmin)
I tried swapping out email for facility
or facilities
or facilitys
, but it seemed pretty obvious that that wouldn't work, and of course it did not. Any one have any advice?
Upvotes: 0
Views: 799
Reputation: 427
In django this feature names related_name or "back reference" in SQLAlchemy. As you can see in docs:
If a model has a ForeignKey, instances of the foreign-key model will have access to a Manager that returns all instances of the first model. By default, this Manager is named FOO_set, where FOO is the source model name, lowercased.
So, in your case you should use facility_set
or redefine related_name
on users
ManyToMany field in Facility
model.
BTW, @schillingt: suggestion to use InlineModelAdmin
much more easy and elegant than anything else.
Upvotes: 1