用户表:
--------------------
| id | name | age |
--------------------
| | | |
--------------------
模特:
class User(models.Model):
name = models.CharField(max_length=30)
age = models.SmallIntegerField()
宠物桌:
--------------------
| id | name | intro |
--------------------
| | | |
--------------------
模特:
class Pet(models.Model):
species = models.CharField(max_length=30)
intro = models.TextField()
现在我要描述这种关系:
用户可以拥有几只宠物(具有独特的种类),我想存储用户获得该宠物的时间。它应该在数据库中看起来像这样:
--------------------------------
| id | user_id | pet_id | since |
--------------------------------
| | | | |
--------------------------------
但我不知道如何在django的模型中描述它......
答案 0 :(得分:2)
您使用“通过”模型。基本上,您可以定义自己的中间表,而不是让Django自动为您执行此操作:
class User(models.Model):
...
pets = models.ManyToManyField(Pet, through='UserPet')
class UserPet(models.Model):
user = models.ForeignKey(User)
pet = models.ForeignKey(Pet)
since = models.DateTimeField(auto_now_add=True)
答案 1 :(得分:0)
试试这个:
class UsersPet(models.Model):
pet = models.ForeignKey(Pet)
user = models.ForeignKey(User)
since = models.DateTime()