简体   繁体   中英

django many to many relationship query reverse

i have a question with django some relationship where i want to use and i am very confused with that task.

i have two tables one table is ball and other table is stadium ,in my problem one stadium maybe to have many balls and one ball maybe to have many stadiums.

here my model :

class ball(models.Model):
    code_ball=models.CharField(max_length=150,unique=True)
    description_ball = models.CharField(max_length=254)
    made_country_ball= models.CharField(max_length=254)
    f_ball= models.CharField(max_length=254)
    rel= models.ManyToManyField(stadium)

class stadium(models.Model):
    code_stadium=models.CharField(max_length=150,unique=True)
    description_stadium = models.CharField(max_length=254)
    made_country_stadium= models.CharField(max_length=254)
    andress_stadium= models.CharField(max_length=254)
    team_stadium= models.CharField(max_length=254)

my question is how to create query views to show that in html templates? for example in some html page need to show all details from table stadium and all or fist code_ball with description_bal from table balls .

i don't know hot to do that because i don't have foreign key for table ball to table stadium ,with some way i need to reverse relationship to create a new query,any idea how ?

If you want to have the full functionality of the ManyToMany fields you should define a through table docs . This does not change anything but shows you what really happens behind the scenes. So you can then use the Foreignkey relation for what you want.

You got to have an associative entity of the two tables.

class ball(models.Model):
    code_ball=models.CharField(max_length=150,unique=True)
    description_ball = models.CharField(max_length=254)
    made_country_ball= models.CharField(max_length=254)
    f_ball= models.CharField(max_length=254)
    rel= models.ManyToManyField(stadium, through='StadiumBall')

class stadium(models.Model):
    code_stadium=models.CharField(max_length=150,unique=True)
    description_stadium = models.CharField(max_length=254)
    made_country_stadium= models.CharField(max_length=254)
    andress_stadium= models.CharField(max_length=254)
    team_stadium= models.CharField(max_length=254)

class StadiumBall(models.Model):
    stadium = models.ForeignKey(stadium, on_delete=models.CASCADE)
    ball = models.ForeignKey(ball, on_delete=models.CASCADE)

Here is a documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM