Mikey079
Mikey079

Reputation: 3

django multiple foreignkeys to the same parent class

I am quite new to Django and I am creating an app which stores unit conversion tables for an application on a mobile device.

Each UnitCategory can have multiple Units, each of which have a multiplication factor to use to convert values between them. The current model could be simplified to this:

class UnitCategory(models.Model):
    name=models.CharField(max_length=100)

class Unit(models.Model):
    name=models.CharField(max_length=200)
    multiplicand=models.FloatField(default=1)
    category=models.ForeignKey('UnitCategory',related_name='units_set')

With admin classes:

class UnitCategoryAdmin(admin.ModelAdmin):
    model=UnitCategory
    inlines=[UnitInline]

class UnitInline(admin.TabularInline):
    model=Unit

Now, rather than entering all of the multiplication factors for all potential units, most of the units in many categories can be built as a function of other base categories, e.g a simple case would be: [Speed] = [Distance] x [Time]^-1.

I am trying to add a class to provide another set of inlines to store data for compound conversion. Each inline would have a dropdown list to select a base unit category and an integer field to enter power it is raised to. I know how to create the dropdown list using a ForeignKey, but I am already using one ForeignKey to link the inline model to the UnitCategory, so I end up with two ForeignKeys pointing to the same parent class:

class CompoundConversionCategory(models.Model):
    parent=models.ForeignKey('UnitCategory',related_name='compounds_set')
    category=models.ForeignKey('UnitCategory',related_name='category_set')
    power=models.IntegerField(default=1)

where the admin classes become:

class UnitCategoryAdmin(admin.ModelAdmin):
    model=UnitCategory
    inlines=[UnitInline,CompoundCategoryInline]

class UnitInline(admin.TabularInline):
    model=Unit

class CompoundCategoryInline(admin.TabularInline):
    class=CompoundConversionCategory

Not surprisingly, Django doesn't like me using two ForeignKeys to the same parent class. Is there a way to specify that one of them should be linked to a different object than the parent, or some other more appropriate way to to create a dropdown list from the model?

Upvotes: 0

Views: 276

Answers (1)

vishen
vishen

Reputation: 469

I believe you are looking for admin.InlineModelAdmin.fk_name. (https://docs.djangoproject.com/en/1.7/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin.fk_name)

Upvotes: 1

Related Questions