Skip to content

Instantly share code, notes, and snippets.

@hirokts
Last active May 10, 2017 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirokts/d79009dedee51e2ad97b0f585057eafd to your computer and use it in GitHub Desktop.
Save hirokts/d79009dedee51e2ad97b0f585057eafd to your computer and use it in GitHub Desktop.
djangoでchoicefield(セレクトボックス)を含むformのformsetを使う場合の選択肢の注入のパターン(model)
class ArticleGroup(models.Model):
title = models.CharField(max_length=255, null=True, blank=True)
@staticmethod
def get_all_article_group_titles():
# articleのタイトルをサマったものをセレクトボックスの選択肢(choice)にする
article_groups = ArticleGroup.objects.all()
groups = []
for article_group in article_groups:
if not article_group.title:
articles = Article.objects.filter(article_group=article_group).all().order_by('pk')
article_group_title = '【{}】'.format(', '.join(['{}. {}'.format(i.value, i.title) for i in articles]))
else:
article_group_title = article_group.title
groups.append((article_group.pk, article_group_title, ))
return groups
class Article(models.Model):
article_group = models.ForeignKey(ArticleGroup, related_name='articles', null=True, blank=True)
title = models.CharField(max_length=128)
value = models.IntegerField()
body = models.TextField()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment