首页 \ 问答 \ Django - 如何将数据添加到ManyToMany字段模型?(Django - How to add data to a ManyToMany field model?)

Django - 如何将数据添加到ManyToMany字段模型?(Django - How to add data to a ManyToMany field model?)

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

models.py:

class Batch(models.Model):
    material_id = models.ManyToManyField(AssetMetadata)
    user = models.ForeignKey(User)

    def __str__(self):
        return 'Batch_' + str(self.pk) + '_' + self.user.username

class AssetMetadata(models.Model):

    material_id = models.CharField(max_length=256, blank=True)
    series_title = models.CharField(max_length=256, blank=True)
    season_title = models.CharField(max_length=256, blank=True)
    season_number = models.IntegerField(default=0)
    episode_title = models.CharField(max_length=256, blank=True)
    episode_number = models.IntegerField(default=0)
    synopsis = models.TextField(max_length=1024, blank=True)
    ratings = models.CharField(max_length=256, blank=True)

    def __str__(self):
        return self.material_id

views.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})

来自模板的片段:

<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模型中。

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

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

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


I have the following models, view and template:

models.py:

class Batch(models.Model):
    material_id = models.ManyToManyField(AssetMetadata)
    user = models.ForeignKey(User)

    def __str__(self):
        return 'Batch_' + str(self.pk) + '_' + self.user.username

class AssetMetadata(models.Model):

    material_id = models.CharField(max_length=256, blank=True)
    series_title = models.CharField(max_length=256, blank=True)
    season_title = models.CharField(max_length=256, blank=True)
    season_number = models.IntegerField(default=0)
    episode_title = models.CharField(max_length=256, blank=True)
    episode_number = models.IntegerField(default=0)
    synopsis = models.TextField(max_length=1024, blank=True)
    ratings = models.CharField(max_length=256, blank=True)

    def __str__(self):
        return self.material_id

views.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})

snippet from template:

<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>

I am trying to get the data provided from the checkbox and save it in the Batch model.

The user selects assets to create a batch, the form returns the pk for these assetss in AssetMetadata and the selections are stored in a list create via batch_list = request.POST.getlist('batch'). I want to use the data stored in this list to create a new entry in Batch which then links to the asset pk in AssetMetadata.

I have been able to do this successfully in the Django admin page but i would ideally do this in teh view.

I have read https://docs.djangoproject.com/en/1.10/ref/models/relations/ and search stackoverflow but i am stumped as how to do this.


原文:https://stackoverflow.com/questions/44409524
更新时间:2022-09-27 14:09

最满意答案

实际上它有trees属性:

import org.apache.spark.ml.attribute.NominalAttribute
import org.apache.spark.ml.classification.{
  RandomForestClassificationModel, RandomForestClassifier, 
  DecisionTreeClassificationModel
}

val meta = NominalAttribute
  .defaultAttr
  .withName("label")
  .withValues("0.0", "1.0")
  .toMetadata

val data = sqlContext.read.format("libsvm")
  .load("data/mllib/sample_libsvm_data.txt")
  .withColumn("label", $"label".as("label", meta))

val rf: RandomForestClassifier = new RandomForestClassifier()
  .setLabelCol("label")
  .setFeaturesCol("features")

val trees: Array[DecisionTreeClassificationModel] = rf.fit(data).trees.collect {
  case t: DecisionTreeClassificationModel => t
}

正如您所看到的,唯一的问题是使类型正确,以便我们可以实际使用这些:

trees.head.transform(data).show(3)
// +-----+--------------------+-------------+-----------+----------+
// |label|            features|rawPrediction|probability|prediction|
// +-----+--------------------+-------------+-----------+----------+
// |  0.0|(692,[127,128,129...|   [33.0,0.0]|  [1.0,0.0]|       0.0|
// |  1.0|(692,[158,159,160...|   [0.0,59.0]|  [0.0,1.0]|       1.0|
// |  1.0|(692,[124,125,126...|   [0.0,59.0]|  [0.0,1.0]|       1.0|
// +-----+--------------------+-------------+-----------+----------+
// only showing top 3 rows

注意

如果您使用管道,您也可以提取单个树:

import org.apache.spark.ml.Pipeline

val model = new Pipeline().setStages(Array(rf)).fit(data)

// There is only one stage and know its type 
// but lets be thorough
val rfModelOption = model.stages.headOption match {
  case Some(m: RandomForestClassificationModel) => Some(m)
  case _ => None
}

val trees = rfModelOption.map {
  _.trees //  ... as before
}.getOrElse(Array())

Actually it has trees attribute:

import org.apache.spark.ml.attribute.NominalAttribute
import org.apache.spark.ml.classification.{
  RandomForestClassificationModel, RandomForestClassifier, 
  DecisionTreeClassificationModel
}

val meta = NominalAttribute
  .defaultAttr
  .withName("label")
  .withValues("0.0", "1.0")
  .toMetadata

val data = sqlContext.read.format("libsvm")
  .load("data/mllib/sample_libsvm_data.txt")
  .withColumn("label", $"label".as("label", meta))

val rf: RandomForestClassifier = new RandomForestClassifier()
  .setLabelCol("label")
  .setFeaturesCol("features")

val trees: Array[DecisionTreeClassificationModel] = rf.fit(data).trees.collect {
  case t: DecisionTreeClassificationModel => t
}

As you can see the only problem is to get types right so we can actually use these:

trees.head.transform(data).show(3)
// +-----+--------------------+-------------+-----------+----------+
// |label|            features|rawPrediction|probability|prediction|
// +-----+--------------------+-------------+-----------+----------+
// |  0.0|(692,[127,128,129...|   [33.0,0.0]|  [1.0,0.0]|       0.0|
// |  1.0|(692,[158,159,160...|   [0.0,59.0]|  [0.0,1.0]|       1.0|
// |  1.0|(692,[124,125,126...|   [0.0,59.0]|  [0.0,1.0]|       1.0|
// +-----+--------------------+-------------+-----------+----------+
// only showing top 3 rows

Note:

If you work with pipelines you can extract individual trees as well:

import org.apache.spark.ml.Pipeline

val model = new Pipeline().setStages(Array(rf)).fit(data)

// There is only one stage and know its type 
// but lets be thorough
val rfModelOption = model.stages.headOption match {
  case Some(m: RandomForestClassificationModel) => Some(m)
  case _ => None
}

val trees = rfModelOption.map {
  _.trees //  ... as before
}.getOrElse(Array())

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)