Как правильно установить отношение относится к петле 3?

Я читал через Wagtail Docs и нашел эту страницу ( http://docs.wagtail.io/en/v2.1.1/advanced_topics/third_party_tutorials.html ), и на этой странице был статья о динамических шаблонах. Это страница, которая имеет его: https://www.coactivate.org/projects/ejucovy/blog/2014/05/10/wagtail-notes-dynamic-templates-per-page/

Идея состоит в том, чтобы установить CharField и позволить пользователю выбрать свой шаблон. В следующем примере они используют раскрывающийся список, который может быть даже лучше для вас.

class CustomPage(Page):

    template_string = models.CharField(max_length=255, choices=(
                                         (”myapp/default.html”, “Default Template”), 
                                         (”myapp/three_column.html”, “Three Column Template”,
                                         (”myapp/minimal.html”, “Minimal Template”)))
    @property
    def template(self):
        return self.template_string 

^ код с сайта coactivate.org, это не мое дело.

В свойстве шаблона вы можете проверить if not self.template_string: и установить свой по умолчанию путь туда.

Редактировать # 1: Добавить наследование страницы.

Вы можете добавить родительскую страницу (базовый класс) и изменить ее, а затем расширить любой другой класс с помощью нового базового класса. Вот пример:

class BasePage(Page):
    """This is your base Page class. It inherits from Page, and children can extend from this."""

    template_string = models.CharField(max_length=255, choices=(
                                         (”myapp/default.html”, “Default Template”), 
                                         (”myapp/three_column.html”, “Three Column Template”,
                                         (”myapp/minimal.html”, “Minimal Template”)))
    @property
    def template(self):
        return self.template_string 


class CustomPage(BasePage):
    """Your new custom Page."""

    @property
    def template(self):
        """Overwrite this property."""
        return self.template_string 

Кроме того, вы можете установить BasePage как абстрактный класс, чтобы ваши миграции не создавали таблицу базы данных для BasePage (если она используется только для наследования)

0
задан Jonathan Andreu 18 January 2019 в 18:41
поделиться

1 ответ

Возможно, я ошибаюсь, но два отношения принадлежат для меня ничего не значат ... Вот что я бы сделал вместо этого:

В KartParticipation.json:

"clientParticipation": {  //starts the included relation with a lowerCase might be best practice, tho
      "type": "belongsTo",
      "model": "ClientParticipation",
      "foreignKey": "" //you don't need to precise a custom foreign if you use the classic one (easiest to read, imo)
    }

В ClientParticipation.json:

"kartParticipation": {
      "type": "hasOne",
      "model": "KartParticipation",
      "foreignKey": ""
    }

Затем, чтобы добавить отношение:

ClientParticipation.findOne({where: {id: 'your_id'}}, function (err, clientParticipation) {
                if (err)
                    return cb(err, null);

                if (clientParticipation && clientParticipation.id) {
                    var newKartParticipation = {'object_with': 'your_datas'};
                    clientParticipation.kartParticipation.add(newKartParticipation); // this is the code you were seeking, tho
                }
            });

Наконец, вы можете проверить, существует ли отношение, запросив

[113 ]

или программно:

ClientParticipation.findOne({where: {id: 'your_id'}, include : 'kartParticipation'}, function (err, clientParticipation) {
    console.log(clientParticipation.kartParticipation);
});
0
ответ дан F3L1X79 18 January 2019 в 18:41
поделиться
Другие вопросы по тегам:

Похожие вопросы: