N
N
NewNikGit2018-03-30 20:45:21
Django
NewNikGit, 2018-03-30 20:45:21

How to extract data from ManyToManyField?

There is a model:

class Files_sv(models.Model):
    users = models.ManyToManyField(Files)
    current_user = models.ForeignKey(User, related_name='filessv', null=True)

    @classmethod
    def add_files(cls, current_user, new_friend):
        friend, created = cls.objects.get_or_create(
            current_user=current_user
        )

        friend.users.add(new_friend)

    @classmethod
    def remove_files(cls, current_user, new_friend):
        friend, created = cls.objects.get_or_create(
            current_user=current_user
        )

        friend.users.remove(new_friend)

Here a model is created that has 2 attributes:
The first one stores the user, the second - the list of music that he has chosen.
How to display user-selected music?
Tried like this:
def mymusic(request):
    music = Files_sv.objects.filter(current_user=request.user)
    args = {
        'musics': music
    }
    return render(request, "home/homemy.html", args)

And in HTML:
{% for music in musics %}
                            {% if music.users.image %}
                                <img src="{{ music.users.image.url }}" width="150" height="150">
                            {% endif %}
                            <h2><b>Название:</b>{{music.users.text}} - Опубликовано: {{ music.users.data_time }}</h2>
                            <audio controls>
                                <source src="{{music.users.our_file.url}}" type="audio/mp3">
                            </audio>
                            <h3>Опубликовал: {{ music.users.user.get_full_name }}</h3>         
{% endfor %}

But it doesn't output anything

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2018-03-30
@NewNikGit

Good evening, `music.users` is a queryset, you need to go through it in a cycle. Try like this:

{% for music in musics %}
    {% for user in music.users.all %}
        {% if user.image %}
            <img src="{{ user.image.url }}" width="150" height="150">
        {% endif %}
        <h2><b>Название:</b>{{user.text}} - Опубликовано: {{ user.data_time }}</h2>
        <audio controls>
            <source src="{{ user.our_file.url }}" type="audio/mp3">
        </audio>
        <h3>Опубликовал: {{ user.user.get_full_name }}</h3>
     {% empty %}
        Пусто
    {% endfor %}
{% endfor %}

In general, a strange field name:
Probably this field should be called `files`

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question