django - 多对多和一对多的关系

时间:2015-04-27 08:04:24

标签: django database many-to-many many-to-one

我在django工作,正计划为用户提供数据库。

  • 每个用户可以在多个 Rides (随着时间的推移),每个 Ride 可以有多个用户

  • 此外,对于每次骑行,必须只有一个驱动程序(也是用户),所以我认为我之间存在多对多关系有关用户的内容与乘坐的Rides和Users表,以及Rides的Driver_id之间的一对多关系和User_id。右

我的问题是 -

  1. 我在django文档中看到,我应该在 One 模型中添加多对多字段。哪一个重要?还有,它是否创建了一个像rides_users这样的新表?

  2. 此外,使用 foreignKey 字段和 OneToManyField 一对多关系) > field?

  3. 修改

    目前,有我的模特:

    def get_image_path(models.Model):
        return os.path.join('photos',str(instance.id),filename)
    
    
    class UserProfile(models.Model):
        user=models.OneToOneField(User)
        phone_number=models.CharField(max_length=12)
        profile_picture=models.ImageField(upload_to=get_image_path, black=True, null=True)
    
    class Ride(models.Model):
        driver=models.ForeignKey(UserProfile, related_name="r_driver")
        destination=models.ForeignKey(Destination, related_name="r_final_destination")
        leaving_time=models.DateTimeField()
        num_of_spots=models.IntergerField()
        passengers=models.ManyToMany(UserProfile, related_name="r_passengers")
        mid_destinations=models.ManyToMany(Destination, related_name="r_mid_destinations")
    
    class Destination(models.Model):
        name=models.CharField(max_length=30)
    

    如您所见,每个Ride都有多个 mid_destination和多个乘客。 a Ride还有一个驱动程序和一个最终目标。

    问题是 - 用户添加 Ride 时,我想要驱动程序目的地 mid_destinations 以及用户设置的其他字段(驱动程序是用户添加Ride),对于乘客字段。我希望其他用户将自己添加到骑行中,因此当创建骑行时,用户(驾驶员)不必设置乘客。

    我该如何解决?还有,关于模特的任何其他建议?

2 个答案:

答案 0 :(得分:0)

没有OneToManyField这样的东西。

从实际角度来看,ManyToManyField所在的哪一方并不重要。就个人而言,我会把它放在Ride上,以避免改变用户模型,因为从概念上讲,我认为游乐设施是这里的主要对象。

是的,添加该字段将自动创建链接表。

答案 1 :(得分:0)

你想要的可能是这样的

    blue  // Result of echo $mavariable
    Chaine nouvelle :body{     
    Chaine nouvelle :    background-color:".$mavariable.";
    Chaine nouvelle : font-size: 18px;
    Chaine nouvelle :    font-family: cursive;
    Chaine nouvelle :}}}