Coder 477 Coder 477 - 2 months ago 9
MySQL Question

Referencing an object of a model with all foreign keys in Django admin UI

I am developing my Djnago app for processing data into DB from admin frontend.
I have a table with both foreign keys in it.

class exam_questions(models.Model):
exam_id=models.ForeignKey(exams, on_delete=models.CASCADE)
question_id=models.ForeignKey(questions, on_delete=models.CASCADE)
def __int__(self):
return self.exam_id


When I am trying to return the above field it is shown in admin UI as exam_questions object for all values added into table.
Is there a way to get the actual value of the column displayed in admin UI.

I have other tables which have different definitions and I am able to display the required field from that. The issue is observed only when all keys in model are foreign keys

Any help is appreciated.

Answer

You need to provide the __str__ or __unicode__ functions, with regard to your python version, in a model for Django admin to be able to list items with their proper intended information.

@python_2_unicode_compatible
class exam_questions(models.Model):
    exam_id=models.ForeignKey(exams, on_delete=models.CASCADE)
    question_id=models.ForeignKey(questions, on_delete=models.CASCADE)

    def __int__(self):
        return self.exam_id

    def __str__(self):
        return '%s - %s' % (self.exam_id.name, self.question_id.name)

If you're coding with cross version compatibility, you need to decorate your model with @python_2_unicode_compatible, and only override the __str__ method.

Anyways but, why your ForeignKeys have _id in them ? Django automatically adds the _id to FKs that points to the id of the related instance.