so I’m doing a small django project and I’m running into a few problems when trying to place certain models inline in the admin site. Eg:
models.py
class Client(models.Model):
client_name = models.CharField(max_length=100,unique=True,blank=False)
phone_number = models.ForeignKey(Phone)
class Phone(models.Model):
info = models.Charfield("eg. Personal", max_length=20)
number = models.CharField(max_length=20, blank=False)
now if I want to have my client admin with a phone_number stacked inline I can’t do that,… and instead I need to have my models like this:
class Client(models.Model):
client_name = ...
class PhoneAbstract(models.Model):
info = ...
number = ...
class Meta:
abstract = True
class ClientPhone(PhoneAbstract):
client = models.ForeignKey(Client)
…and basically define a new class that inherits from PhoneAbstract every time I want to relate a phone with a model :(. This sucks but it’s the only way in which I can then do this and get the proper admin interface:
admin.py
class PhoneInline(admin.TabularInline):
model = ClientPhone
class ClientAdmin(admin.ModelAdmin):
inlines = (PhoneInline, )
Now, this is ugly as hell (to my still uneducated eyes) and it makes the relationships awkward… so, is there a way of having the foreign keys in my ClientAdmin in the first case? maybe this is what ModelAdmin.list_select_related is for, but I am not sure… 🙁
I’ve no idea why you want to define things this way round. The way you want to have it, one phone number can belong to multiple clients, which seems unlikely. Having the ForeignKey field on the PhoneNumber model is the right thing to do, because that way the relationship makes sense (a client can have multiple phone numbers).
But there’s no need to muck about with abstract models and subclassing. If you need the ability for a phone number to point to multiple different model classes, then generic relations are what you need.