我正在构建一个应用程序,其中我具有通过多对多关系链接到另一个模型的模型。这是一个例子: 我有一个体育训练课,包括多个练习,例如:
当我将练习添加到会话中时,它们会添加到前面(有角),但是当我刷新页面时,每个对象中只有一个副本保留在会话对象中。
以下是模型:
class Exercice(models.Model):
name = models.CharField(max_length=255)
class Session(models.Model):
sequences = models.ManyToManyField(Exercice, null=True, blank=True)
关于在一个会话中具有多次相同练习的任何想法吗?
答案 0 :(得分:1)
这是因为m2m仅包含ID,而不是您想要ID和订单的次数。
问题似乎与您的数据库结构更相关。
似乎您需要一个新表来存储此信息。
def create_auction(request):
if request.method == 'POST':
form = AuctionsForm(request.POST)
if form.is_valid():
auction = form.save(commit=False)
# do something if you but in the end
auction.save()
# do want you want here, or return in to creation page dunno
return render(request, "success?idk/", {"auction": auction})
else:
# maybe you want to render the errors?
# https://stackoverflow.com/questions/14647723/django-forms-if-not-valid-show-form-with-error-message
return render(request, "auctions/create.html", {"form": form})
form = AuctionForm()
return render(request, "auction/create.html", {"form":form})
# maybe you had listing view here
然后,您可以遍历此表以获取所需的内容。
因此在后端中,当您创建会话时,您还应该为其中的每个练习创建序列条目
您现在可以通过查看以下内容来访问序列:
class Exercice(models.Model):
name = models.CharField(max_length=255)
class Session(models.Model):
exercices = models.ManyToManyField(Exercice, null=True, blank=True)
class Sequence(models.Model):
exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE)
session = models.ForeignKey(Session, on_delete=models.CASCADE)
#any extra info there
repetitions = models.PositiveSmallIntegerField(blank=True, null=True) #how many time each?
created_at = models.DateTimeField(auto_now_add=True) # used to generate the sequence of exercices
答案 1 :(得分:0)
您正尝试创建一种类型的历史记录表,而不是实际映射。您可以在下面添加一个中间件模型。
class ExerciseHistory(models.Model):
exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE)
session = models.ForeignKey(Session, on_delete=models.CASCADE)
created_date = models.DateTimeField(auto_now_add=True)