好球員,我有兩個不同的模式:django中的多對多關係;從一個對象指的另一個
class topic(models.Model):
learningObjectivesTopic = models.ManyToManyField(learningObjective, verbose_name = "Lernziel")
topic = models.TextField(verbose_name = 'Thema')
和
class learningObjective(models.Model):
learningObjectives = models.TextField(verbose_name = 'Lernziel')
非常基本的。我的目標是爲屬性「主題」創建主題,然後在我想創建新的學習目標時參考它們。我的觀點顯然無法按照我希望他們工作的方式工作,但我會張貼他們稍後解釋我的目標是什麼。
from django.shortcuts import render
from programm.models import *
from django.contrib.auth.decorators import login_required
@login_required(login_url='login')
def lernziel(request):
return render(request, 'lernziel.html', {'topic': topic.objects.all()})
@login_required(login_url='login')
def create_lernziel(request):
neuesLernziel=learningObjective(learningObjectives=request.POST["Lernziel"])
neuesLernziel.save()
neuesLernziel_Topic=topic(topic=request.POST["Thema"])
neuesLernziel_Topic.save()
neuesLernziel_Topic.learningObjectivesTopic.add(neuesLernziel)
return render(request, 'lernziel.html', {'topic': topic.objects.all()})
@login_required(login_url='login')
def themen(request):
return render(request, 'themen.html', {'thema': topic.objects.all()})
@login_required(login_url='login')
def create_themen(request):
neueThemen=topic(topic=request.POST['Thema'])
neueThemen.save()
return render(request, 'themen.html', {'thema': topic.objects.all()})
我以爲這一行:
neuesLernziel_Topic.learningObjectivesTopic.add(neuesLernziel)
我可以指一個學習目標,對此我要創造,要和現有的話題。但是看起來,我的django視圖只是使用新的id創建一個新條目,而不是使用具有相同值和舊ID的舊條目。爲了更清楚:我有:topic1和topic2。我想現在提及4個學習目標。例如lObj 1和3到topic 1和lobj 2和4到topic 2.會發生什麼情況,目前django在主題表中創建了4個新的entrys。它現在包含3個值,topic1和3的值分別爲topic2。它應該仍然是2 entrys,在許多表中它應該使用odl id。如果您需要了解更多信息或者如果事情還不清楚,請把它寫:)
順便說一句,我這兩個模板接收數據: lernziel.html:
<!DOCTYPE html>
<html lang="{{ LANGUAGE_CODE|default:"de-de" }}" >
<head>
<h1 align = "center">Lernziele</h1>
</head>
<body>
<form action="{% url 'create_lernziel' %}" method="post">
{% csrf_token %}
<br>Hallo Benutzer: {{ user.username }}</br>
Lernziel: <textarea name="Lernziel" rows="3" cols="45" ></textarea>
<p>
<select name="Thema" size="3">
{% for topic_ in topic %}
<option>{{ topic_.topic }}</option>
{% endfor %}
</select>
</p>
<input type="submit" value="Absenden" />
</form>
<table border="1">
<th>Lernziel</th>
<th>Thema</th>
{% for topic_ in topic %}
<tr>
{% for lObj in topic_.learningObjectivesTopic.all %}
<td>{{ lObj }}</td>
{% endfor %}
<td>{{ topic_.topic }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>
和themen.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<br>Hallo Benutzer: {{ user.username }}</br>
<form action="{% url 'create_themen' %}" method="post">
{% csrf_token %}
<br>Thema: <textarea name="Thema" rows="3" cols="45"></textarea></br>
<input type="submit" value="Absenden" />
</form>
</br>
<table border="1">
<th>Thema</th>
{% for thema_ in thema %}
<tr>
<td>{{ thema_.topic }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>