class没有类的外键

时间:2014-08-22 10:37:53

标签: python django django-admin

我的Django Models设置如下:

class Cities(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, unique=True)

    def __unicode__(self):
        return self.name


class Pincode(models.Model):
    id = models.AutoField(primary_key=True)
    pin = models.CharField(max_length=20, unique=True)

    def __unicode__(self):
        return self.pin


class Address(models.Model):
    id = models.AutoField(primary_key=True)
    build_add = models.CharField(max_length=255)
    street_add = models.CharField(max_length=255)
    area = models.CharField(max_length=255)
    city = models.ForeignKey(Cities)
    pin = models.ForeignKey(Pincode)

    def __unicode__(self):
        return self.area


class Classified(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=256)
    contact_person = models.CharField(max_length=300, blank=True)
    email = models.CharField(max_length=100, blank=True)
    address = models.ForeignKey(Address)
    subcategory = models.ForeignKey(Subcategory)
    area_code = models.CharField(max_length=10, blank=True,  default='')
    phone_number = models.BigIntegerField(max_length=20, default=0, blank=True)
    secondary_number = models.BigIntegerField(max_length=20, default=0, blank=True)
    more_numbers = models.CharField(max_length=300, default='', blank=True)
    image = S3DirectField(upload_to='s3direct', blank=True)
    secondary_image = S3DirectField(upload_to='s3direct', blank=True, default='')
    description = models.TextField(max_length=1000, blank=True)
    location = LocationField(blank=True, max_length=255)
    NO = 'NO'
    YES = 'YES'
    APPROVAL = ((NO, 'no'), (YES, 'yes'))
    active = models.CharField(choices=APPROVAL, default=NO, max_length=3)
    verified = models.CharField(choices=APPROVAL, default=NO, max_length=3)

我的问题与执行内联有关,因为我需要在Classified中的每个条目的数据,以便在管理员本身的Classified视图中进行编辑。

我已尝试以下操作在同一视图中编辑地址

class AddressInline(admin.TabularInline):
    model = Address


class ClassifiedAdmin(admin.ModelAdmin):
    inlines = [AddressInline, ]
    search_fields = [
        'name',
    ]


admin.site.register(Classified, ClassifiedAdmin)

然而,这给了我以下错误:

<class 'appname.models.Address'> has no ForeignKey to <class'appname.models.Classified'>

如何解决此错误?我查看并尝试了<class> has no foreign key to <class> in Django when trying to inline modelsInline in Django admin: has no ForeignKey的解决方案,但它们似乎对我不起作用。

1 个答案:

答案 0 :(得分:1)

你的内联可能是错误的。内联应该用于依赖模型实例。因此,您可以在Classified中使用Address,但不能相反,因为Classified依赖于具有外键关系的Address。如果您有外键关系,则可以只使用常规字段,表单最后会有一个用于选择地址的选择框。如果你真的希望一个Classified对象出现在多个addresess中,那么使用ManyToManyField而不是ForeignKey,然后Django会自动为你生成一个中间表。

此外,您的代码中不需要AutoField行。 Django默认会生成一个自动递增的主键,其属性名称为“id”。