views:

31

answers:

1

I have two models and one admin model:

class Person(models.Model):

    firstname = models.CharField(maxlength=50)
    surname = models.CharField(maxlength=50)

class Friends(models.Model):

    person1 = models.ForeignKey("Person")
    person2 = models.ForeignKey("Person")
    friendship_made = models.DateField()

class PersonAdmin(admin.ModelAdmin):
    list_display = ["firstname", "surname"]

I want to show the friend of the person in the list_display. I know if I had the foreignkey field in the Person model I could use the double underscore to reference it e.g. person2__surname. But not sure how to do it when thr foreign key is in the other table.

In my system one person can only be friends with one person at a time so it would be better if the foreignkey was in the person model but I want to store extra info about the friendship such as the date it was made (firendship_made) so this is why I've put it in a seperate model. Any advise? If I have to change my models to get the best result I don't mind.

A: 

This code isn't complete - you've got two ForeignKeys from Friends to Person, so at least one of them will need a related_name attribute to prevent clashes. The code simply won't run as it is.

If a Person can only be friends with one other person, you should use a OneToOneField rather than a ForeignKey. Then, you can simply refer to my_person.friend1.person1.surname, where my_person is the Person you starting with, and friend1 is the related_name value I mentioned above.

Daniel Roseman