Last active
May 10, 2017 02:18
-
-
Save hirokts/d79009dedee51e2ad97b0f585057eafd to your computer and use it in GitHub Desktop.
djangoでchoicefield(セレクトボックス)を含むformのformsetを使う場合の選択肢の注入のパターン(model)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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