0

I have to work with a legacy database and have the following problem. My model has a foreign key to the User Model:

class History(models.Model):
    uid = models.ForeignKey(User, to_field='username', db_column='uid')

That seems to work. The Problem is that for some History entries the User entry doesn't exist anymore. Is there an easy solution?

The Application seems to work fine with it. The only problem is in the Admin-Interface of the Model:

class HistoryAmdin(admin.ModelAdmin):
    list_display = ('id', 'uid')

It shows only entries with a valid foreign key. Is it possible to show also the other entries?

ilse2005
  • 11,189
  • 5
  • 51
  • 75

1 Answers1

2

Set you null=True inside your History class.

class History(models.Model):  
    uid = models.ForeignKey(User, to_field='username', db_column='uid', null=True)
bluszcz
  • 4,054
  • 4
  • 33
  • 52
  • Thanks! Now the entries are shown in the admin-interface. But the "uid" field is shown as "emtpy". Is it possible to show the actual string entry for those data-sets? – ilse2005 Feb 20 '14 at 10:00
  • Where? On listing of HistoryAdmin or where? – bluszcz Feb 20 '14 at 10:28
  • Yes, on listing of HistoryAdmin – ilse2005 Feb 20 '14 at 10:43
  • Not sure what do you mean by "show actual string entry" - if value is a null. Maybe - but I can't check now since I am at work but try "list_display = ('id', 'uid__username') or something similar and please marked answer if it helped you :) – bluszcz Feb 20 '14 at 10:56
  • Maybe I clarify a bit: I have a history table and there is Column "uid". In my legacy database there is a value for "uid" for every entry. But for some "uid" Entries there is no corresponding User object. If I use your suggestion "null=True", I'll see in listing of HistoryAdmin all Entries, those with no existing User too. But for those the entry of "uid" shows "empty". Which is reasonable because no User object could be found. But the actual table field "uid" has a string value which I want to display in this case. I hope now it's clearer what I'm trying to do. – ilse2005 Feb 20 '14 at 11:07
  • OK I solved it like this: def uid_or_str(self,instance): try: isinstance(instance.uid,User) return instance.uid except: return History.objects.values_list('uid',flat=True).filter(id=instance.id) – ilse2005 Feb 20 '14 at 12:58