在 Django 中使用另一个关系 table 连接两个 table
join two tables using another relation table in Django
我在管理面板中遇到 list_display 问题。
class Categories(models.Model):
cat_id = models.IntegerField(primary_key=True)
cat_name = models.CharField(_('category name'), max_length=50)
def __unicode__(self):
return self.cat_name
class Stories(models.Model):
story_id = models.IntegerField(primary_key=True)
story_title = models.CharField(max_length=500)
story_desc = models.TextField()
cover_image = models.CharField(max_length=500)
date_of_creation = models.DateTimeField(auto_now_add=True)
date_of_publish = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.story_title
class Relation(models.Model):
tbl_id = models.IntegerField(primary_key=True)
story_id = models.ForeignKey(Stories)
cat_id = models.ForeignKey(Categories)
我想在 mysql 中使用关系 table 连接两个 table、故事和类别。但我不想在 Relation table.
中再添加任何列
此外,我想在管理面板中列出-
class StoryAdmin(admin.ModelAdmin):
list_display = (story_title, story_desc, date_of_creation, cat_name)
admin.site.register(Relation, StoryAdmin)
你看过这个吗:
https://docs.djangoproject.com/en/1.7/topics/db/models/#extra-fields-on-many-to-many-relationships
还有这个:
django: how does manytomanyfield with through appear in admin?
您可以使用 ManyToMany
字段管理您的关系。此外,您获取 cat_name
的方式也是错误的,因为该属性不属于 Story table。您应该创建一个函数来获取一个故事的所有类别(即字符串连接),然后将该函数添加到 list_display
.
我在管理面板中遇到 list_display 问题。
class Categories(models.Model):
cat_id = models.IntegerField(primary_key=True)
cat_name = models.CharField(_('category name'), max_length=50)
def __unicode__(self):
return self.cat_name
class Stories(models.Model):
story_id = models.IntegerField(primary_key=True)
story_title = models.CharField(max_length=500)
story_desc = models.TextField()
cover_image = models.CharField(max_length=500)
date_of_creation = models.DateTimeField(auto_now_add=True)
date_of_publish = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.story_title
class Relation(models.Model):
tbl_id = models.IntegerField(primary_key=True)
story_id = models.ForeignKey(Stories)
cat_id = models.ForeignKey(Categories)
我想在 mysql 中使用关系 table 连接两个 table、故事和类别。但我不想在 Relation table.
中再添加任何列此外,我想在管理面板中列出-
class StoryAdmin(admin.ModelAdmin):
list_display = (story_title, story_desc, date_of_creation, cat_name)
admin.site.register(Relation, StoryAdmin)
你看过这个吗:
https://docs.djangoproject.com/en/1.7/topics/db/models/#extra-fields-on-many-to-many-relationships
还有这个:
django: how does manytomanyfield with through appear in admin?
您可以使用 ManyToMany
字段管理您的关系。此外,您获取 cat_name
的方式也是错误的,因为该属性不属于 Story table。您应该创建一个函数来获取一个故事的所有类别(即字符串连接),然后将该函数添加到 list_display
.