How To Create Many-to-one Relation With Django And To Display It In Admin Interface
Solution 1:
Add the related_name parameter to your ForeignKey on WebsiteIP like so:
classWebsite(models.Model):
name = models.CharField(max_length = 100)
classWebsiteIp(models.Model):
website = models.ForeignKey(Website, primary_key = True, related_name="IPs")
ip = models.CharField(max_length = 40)
introduction_date = models.DateField()
Then, you can reference the IPs as a many-to-one mapping from Website like so:
website = Website.objects.filter(name="blah")
if website.count():
IPs = website[0].IPs
Untested of course, but this should get you in the right direction. Also check out: https://docs.djangoproject.com/en/dev/topics/db/models/#many-to-one-relationships
In your admin.py, where you presumably have something like this:
class WebsiteAdmin(admin.ModelAdmin):
list_display = ('name',)
search_fields = ['name']
ordering = ('name', )
Update to the following:
classWebsiteIpInline(admin.TabularInline):
model = WebsiteIpextra=1classWebsiteAdmin(admin.ModelAdmin):
list_display = ('name',)
search_fields = ['name']
inlines = ( WebsiteIpInline, )
ordering = ('name', )
Should display what you want!
Solution 2:
Work around this problem is to modify primary key settings on dependant relation (but that works only in cases like this - when there is one piece of key that might be unique for entire table (ip in this case)).
classWebsiteIp(models.Model):
website = models.ForeignKey(Website)
ip = models.CharField(max_length = 40, primary_key = True)
introduction_date = models.DateField()
After this (and only after this), part of solution proposed by mkoistinen would work in expected way. General problem is that django is checking ability to create new objects by examining uniqueness of primary key columns (in a wrong way), so I guess it is possible to fix that too by overriding some of models.Model methods, but I don't know enough about django internals to be able to point what method.
Post a Comment for "How To Create Many-to-one Relation With Django And To Display It In Admin Interface"