在 Django Telmplates 中使用外键作为对象

Using foreign key as object in Django Telmplates

我正在尝试使用 django rest 框架构建一个结构,以便在我的 html 模板中显示一些数据。但是我无法显示来自带有外键的模型的数据。

我的结构应该是这样的:

{% for category in categories %}
    {{ category.category }} #category is the variable name
    {% for channel in category.channel_set.all %}
        {{ channel.title }}
    {{ endfor }}
{{ endfor }}

但我无法在 html 文件中打印通道变量。

models.py:

class Category(models.Model):
    user = models.ForeignKey(
        'auth.User', 
        on_delete=models.DO_NOTHING,
        unique=False,
        )
    category = models.CharField(
    max_length=255,
    unique=True,
    )
    _id = models.ObjectIdField(auto_created=True, serialize=False)

    event_creation = models.DateTimeField(auto_now=True)
    event_updated = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'category'
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.category

class Channel(models.Model):
        user = models.ForeignKey(
            'auth.User', 
            on_delete=models.DO_NOTHING,
            )
        _id = models.ObjectIdField(auto_created=True, serialize=False)
        date_creation = models.DateTimeField(auto_now=True)
        date_updated = models.DateTimeField(auto_now=True)
        category = models.ForeignKey(
            Category,
            max_length=255,
            on_delete=models.PROTECT,
            related_name='channel',
            unique=False,
            to_field='category',
            )
        channel = models.CharField(
            max_length=255,
            unique=True,
            )
        def __str__(self):
            return self.category

views.py:

class Gallery(viewsets.ModelViewSet):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = '/gallery.html'
    queryset = Category.objects.all()
    queryset2 = Channel.objects.all()
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request, **kwargs):
        kwargs['categories_list'] = self.queryset
        serializer = CategorySerializer(self.queryset,many=True)
        serializer2 = ChannelSerializer(self.queryset2,many=True)
        return Response({
            'categories':serializer.data,
            'channels':serializer2.data
            })

    # @login_required(login_url='/login/')
    def list(self, request):
        queryset = Category.objects.all()
        response = {'categories': queryset}
        return Response({'categories':queryset})

serializers.py:

class CategorySerializer(serializers.ModelSerializer):
    # _id = serializers.ReadOnlyField()
    categories = Category()
    class Meta:
        model = Category
        fields = '__all__'

class ChannelSerializer(serializers.ModelSerializer):
    # _id = serializers.ReadOnlyField()
    channels = Channel()
    class Meta:
        model = Channel
        fields = '__all__'

gallery.html:

{% extends "/model-page.html" %}

{% load core_tags %}

{% block content %}

<h1> co. </h1>
<h2> Last Archives </h2>

<a href="/category-api/">
    <button type="button"> New input </button>
</a>
<ul>
    {% for category in categories %}
    <td> {% underscoreTag category "_id" as category_id %} </td>
    <div {% if category.get_pass_event %} style="color: red "{% endif %}>
        <li>{{ category.category }} - {{ category.get_creation }}
                <ul>
                    <li>{{ category }}</li>
                    <ul>
                        <div>
                            {% for channel in category.channel_set.all %}
                                <li>Teste {{ channel.title }}</li>
                           
                            {% endfor %}
                        </div>
                    </ul>
                </ul>
                    <a href="/category/?id={{category_id}}&{{category.category}}">Edit</a> / 
                    <a href="/category/delete/{{category_id}}">Delete</a>
                
            </li>
        </div>
    {% endfor %}
</ul>

{% endblock %}

我尝试过{% for channel in category.channel_set.all %}、{% for channel in category.channels_set.all %}、{% for channel in category.channel.all %} 和 {%对于 category.channels.all %} 中的频道,其中任何一个都对我有用。

我的项目的另一个信息是我正在使用 djongo(因为我的数据库是 mongodb)。

我接受任何帮助,现在谢谢!!

我认为序列化程序的代码不正确。

class ChannelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Channel
        fields = '__all__'

class CategorySerializer(serializers.ModelSerializer):
    channel = ChannelSerializer(many = True, read_only = True)

    class Meta:
        model = Category
        fields = '__all__'

而在 html 中,某些属性在模型中不存在。 channel_set应改为channelchannel.title应改为channel.channel。 模型中没有 channel_settitle 等名称。

...
<ul>
    <div>
        {% for channel in category.channel %}
            <li>Teste {{ channel.channel }}</li>                           
        {% endfor %}
    </div>
</ul>
...

或者您应该修改模型中的名称。