我试图编写一个可以与自身建立多对多关系的Django模型。
这是我的 models.py :
class Apps(models.Model):
name = models.CharField(
verbose_name = 'App Name',
max_length = 30
)
logo = models.ImageField(
verbose_name = 'Logo'
)
description = models.TextField(
verbose_name = 'Description'
)
google_url = models.URLField(
verbose_name = 'Google Play Link',
null = True
)
apple_url = models.URLField(
verbose_name = 'Apple AppStore Link',
null = True
)
youtube_url = models.URLField(
verbose_name = 'Youtube Video Page',
null = True
)
similar_apps = models.ManyToManyField(
'self',
through = 'SimilarApps',
related_name = 'similar_apps',
verbose_name = 'Similar Apps',
help_text = 'Similar Apps',
symmetrical = False
)
def __unicode__(self):
return u'%s' % (self.user.name)
class SimilarApps(models.Model):
primary = models.ForeignKey(
Apps,
verbose_name = 'Primary App',
related_name = 'primary_app',
help_text = 'First of 2 similar Apps.',
)
secondary = models.ForeignKey(
Apps,
verbose_name = 'Matched App',
related_name = 'matched_app',
help_text = 'Second of 2 similar Apps.',
)
当我运行manage.py makemigrations
时,我收到以下错误
<class 'appsrfun.admin.SimilarAppsInline'>: (admin.E202) 'appsrfun.SimilarApps' has more than one ForeignKey to 'appsrfun.Apps'.
appsrfun.Apps.similar_apps: (fields.E302) Reverse accessor for 'Apps.similar_apps' clashes with field name 'Apps.similar_apps'.
HINT: Rename field 'Apps.similar_apps', or add/change a related_name argument to the definition for field 'Apps.similar_apps'.
appsrfun.Apps.similar_apps: (fields.E303) Reverse query name for 'Apps.similar_apps' clashes with field name 'Apps.similar_apps'.
HINT: Rename field 'Apps.similar_apps', or add/change a related_name argument to the definition for field 'Apps.similar_apps'.
请告诉我这是可能的,并解释如何做到这一点。感谢
答案 0 :(得分:0)
This has just got through makemigrations
and I'm going to test it:
class App(models.Model):
name = models.CharField(
verbose_name = 'App Name',
max_length = 30
)
logo = models.ImageField(
verbose_name = 'Logo'
)
description = models.TextField(
verbose_name = 'Description'
)
google_url = models.URLField(
verbose_name = 'Google Play Link',
null = True
)
apple_url = models.URLField(
verbose_name = 'Apple AppStore Link',
null = True
)
youtube_url = models.URLField(
verbose_name = 'Youtube Video Page',
null = True
)
similar_app = models.ManyToManyField(
'self',
through = 'MySimilarApp',
verbose_name = 'Similar App',
help_text = 'Similar App',
symmetrical = False,
through_fields = ('primary','secondary'),
)
def __unicode__(self):
return u'%s' % (self.user.name)
class MySimilarApp(models.Model):
primary = models.ForeignKey(
App,
verbose_name = 'Primary App',
related_name = 'primary_app',
help_text = 'First of 2 similar Apps.',
)
secondary = models.ForeignKey(
App,
verbose_name = 'Matched App',
related_name = 'matched_app',
help_text = 'Second of 2 similar Apps.',
)