代码之家  ›  专栏  ›  技术社区  ›  Jekson

Django:输出与特定用户关联的视频文件

  •  1
  • Jekson  · 技术社区  · 6 年前

    我有customuser模型名称配置文件和视频文件模型,以及与用户相关的字段。有许多用户帐户,每个用户都可以添加大量视频文件。我需要在模板上显示。html用户。昵称和他所有的视频文件。

    使用者型号。py公司

    class Profile(models.Model):
    
        user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
        nickname = models.CharField(max_length=30, blank=True, verbose_name="Никнэйм")        
        userpic = models.ImageField(upload_to='userpics/', blank=True, null=True)
    

    视频文件。型号。py公司

    class VideoFile(models.Model):
        name = models.CharField(max_length=200,blank=True)
        file = models.FileField(upload_to="vstories/%Y/%m/%d", validators=[validate_file_extension])
        date_upload = models.DateTimeField(auto_now_add = True, auto_now = False, blank=True, null = True)
        descriptions =  models.TextField(max_length=200)
        reports = models.BooleanField(default=False)
        vstories = models.ForeignKey(Profile, blank = True, null = True) 
    

    视图。py公司

    def vstories (request):
        profiles = Profile.objects.all()        
        return render(request, "vstories/vstories.html", {'profiles':profiles})  
    

    模板。html

    {% extends "base.html" %}
    {% block content %}
    
    {% if users %}
    {% for user in users %}
    
    <p>{{ user.profile.nickname}}</p>
    
    {% for vstorie in vstories %}
    <p>{{ vstorie.vstories.url }}</p>
    {%  endfor %}
    
    {%  endfor %}
    {% endif %}
    {% endblock content %}
    

    对于这段视频,我很困惑。或者我选择了错误的沟通方式?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Nazkter    6 年前

    您可以“向后”查找外键。在这种情况下,要访问用户(配置文件)的所有视频,您需要拥有所有配置文件:

    def vstories (request):
        profiles = Profile.objects.all() 
        return render(request, "vstories/vstories.html",{'profiles':profiles})   
    

    然后,在模板中,您可以“向后”访问配置文件和视频文件之间的关系。

    {% for profile in profiles %}
        {% for videofile in profile.videofile_set.all %}
            <p>{{ videofile.file.url }}</p>
        {%  endfor %}
    {%  endfor %}
    

    诀窍在于“\u集”,它允许您反向跟踪关系。

    以下是此类查询集的文档: https://docs.djangoproject.com/en/2.0/topics/db/queries/#following-relationships-backward

        2
  •  1
  •   Jekson    6 年前

    这是我的工作

    {% for profile in profiles %}
        {{ profile.nickname }}
    
        {% for videofile in profile.videofile_set.all %}
            <video width="320" height="240" controls src="{{ videofile.file.url }}">
              Your browser does not support the video tag.
            </video>
        {%  endfor %}
    
    {%  endfor %}