Home > Enterprise >  Django admin panel show ForeignKey data
Django admin panel show ForeignKey data

Time:07-22

I'm trying to display more information in a admin panel and can't I have two models with foreign Key I trying show streets list and add to street name City name

class Street(models.Model):
name = models.CharField(max_length=50, verbose_name='Street')
code = models.IntegerField()
city = models.ForeignKey('City', on_delete=models.PROTECT, null=True)

class Meta:
    managed = True
    db_table = 'street'

def __str__(self):
    return self.name   f'({self.city.name})'

class City(models.Model):
name = models.CharField(max_length=50, verbose_name='City')
code = models.IntegerField()

class Meta:
    managed = True
    db_table = 'city'

def __str__(self):
    return self.name  f' ({self.code})'

CodePudding user response:

If i understood your problem correctly, below code should work. without an image , i'm finding it hard to understand

admin.py

from django.contrib import admin
from .models import Street

class StreetAdmin(admin.ModelAdmin):
    list_display = ('id', 'name', 'city')

admin.site.register(Street, StreetAdmin)

CodePudding user response:

One of the streets was connected to a city that I deleted from a database, that's why I got the error

  • Related