Django - 如何将数据添加到ManyToMany字段模型?

时间:2017-06-07 10:02:52

标签: django

我有以下模型,视图和模板:

models.py:

def assets_in_repo(request):

    asset_list = AssetMetadata.objects.order_by('id').all()
    page = request.GET.get('page', 1)
    paginator = Paginator(asset_list, 50)

    try:
        assets = paginator.page(page)
    except PageNotAnInteger:
        assets = paginator.page(1)
    except EmptyPage:
        assets = paginator.page(paginator.num_pages)

    if request.method == 'POST':

        batch_list = request.POST.getlist('batch')
        print(batch_list)

    return render(request, 'assets_db/assets.html', {'assets': assets})

views.py:

<form method="post">{% csrf_token %}
    <input type="submit" value="Create Batch" align="right">
    <table class="table table-striped" id="myTable">
        <tr>
            <th>ID</th>
            <th>Material ID</th>
            <th>Series Title</th>
            <th>Season Tile</th>
            <th>Season Number</th>
            <th>Episode Title</th>
            <th>Episode Number</th>
            <th>Create Batch</th>
        </tr>
        {%  for i in assets %}<tr>
            <td>{{i.pk}}</td>
            <td><a href="/repo/{{ i.id}}">{{i.material_id}}</a></td>
            <td>{{i.series_title}}</td>
            <td>{{i.season_title}}</td>
            <td>{{i.season_number}}</td>
            <td>{{i.episode_title}}</td>
            <td>{{i.episode_number}}</td>
            <td>
                <input type="checkbox" name="batch" value="{{i.pk}}">
            </td>
        </tr>{% endfor %}
    </table>
    </form>
来自模板的

片段:

Batch

我正在尝试从复选框中获取数据并将其保存在pk模型中。

用户选择资产来创建批处理,表单会在AssetMetadata中返回这些资产的batch_list = request.POST.getlist('batch'),并且选择将存储在通过Batch创建的列表中。我想使用此列表中存储的数据在pk中创建一个新条目,然后链接到AssetMetadata中的资产[ all-delete-orphan, delete-orphan, save-update, replicate, lock, evict ]

我已经能够在Django管理页面中成功完成此操作,但我最好在视图中执行此操作。

我已阅读https://docs.djangoproject.com/en/1.10/ref/models/relations/并搜索stackoverflow,但我很难过如何做到这一点。

3 个答案:

答案 0 :(得分:1)

info = Batch.objects.create(season_title ='foo', .....)
info2= AssetMetadata.objects.create(material_id ='some')
info.material_id.add(info2)

尝试这样的事情

答案 1 :(得分:0)

我认为你需要

250

答案 2 :(得分:0)

感谢两个答案的帮助,我能够让这个工作,这就是我做到的:

def assets_in_repo(request):

    asset_list = AssetMetadata.objects.order_by('id').all()
    page = request.GET.get('page', 1)
    paginator = Paginator(asset_list, 50)

    try:
        assets = paginator.page(page)
    except PageNotAnInteger:
        assets = paginator.page(1)
    except EmptyPage:
        assets = paginator.page(paginator.num_pages)

    if request.method == 'POST':

        batch_list = request.POST.getlist('batch')

        info = Batch.objects.create(user_id=request.user.id)
        for item in batch_list:
            info.material_id.add(item)