Django模型关系健身应用程序

2024-04-26 00:00:53 发布

您现在位置:Python中文网/ 问答频道 /正文

目前我的型号是:

class Workout(models.Model):    
    date = models.DateField()
    routine = models.ForeignKey('Routine')
    def __str__(self):
         return '%s' % self.date

class Routine(models.Model):
    name = models.CharField(max_length=255)
    exercises = models.ManyToManyField('Exercise')
    def __str__(self):
        return self.name

 class Exercise(models.Model):
    name = models.CharField(max_length=255)
    def __str__(self):
        return self.name

我希望用户能够创建一个由日期(训练)指定的新条目。他们还可以创建例程(例程),与日期关联,并填充不同的练习(练习),他们也可以创建。在

这是我不能理解的部分。在

我希望用户,当添加一个新的锻炼,能够选择它是力量锻炼还是有氧运动。力量练习将包括以下领域:成套、重复和重量。像carido一样有长度和速度的领域。在

我不清楚如何将这两种练习与练习课联系起来。在


Tags: 用户nameselfdatemodelreturnmodelsdef
1条回答
网友
1楼 · 发布于 2024-04-26 00:00:53

最常见的方法是创建一个generic relationship,例如:

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Exercise(models.Model):
    name = models.CharField(max_length=255)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    info = GenericForeignKey('content_type', 'object_id')
    def __str__(self):
        return self.name

class StrengthExercise(models.Model):
    sets, reps, weight = (...)

class CardioExercise(models.Model):
    length, speed = (...)

示例用法:

^{pr2}$

OBS:确保您的'django.contrib.contenttypes'中有INSTALLED_APPS(默认情况下启用)。

相关问题 更多 >