Home > Mobile >  How to access the value of a foreign key in a table in django?
How to access the value of a foreign key in a table in django?

Time:11-12

I've 2 tables in a database on phpmyadmin that are connected by a foreign key. The table "bulle" contains the foreign key of the table "site". In enghlish : one "site" can contain some "bulles" (or not) and a "bulle" is always linked to a "site".

class Bulles(models.Model):
id_bulle = models.AutoField(primary_key=True)
num_bulle = models.CharField(max_length=20)
type_bulle = models.CharField(max_length=20)
colories = models.CharField(max_length=20)
latitude = models.FloatField()
longitude = models.FloatField()
date_vidange = models.DateField(
    db_column="date_vidange"
) 
id_depot = models.ForeignKey(
    "Depot", on_delete=models.CASCADE, db_column="id_depot"
)
id_site = models.ForeignKey(
    "Site",related_name='bul', on_delete=models.CASCADE, db_column="Id_site"
)  
class Meta:
    db_table = "bulles"

class Site(models.Model):
id_site = models.AutoField(
    db_column="Id_site", primary_key=True
) 
nom = models.CharField(
    db_column="Nom", max_length=100
) 
vitesse_b = models.FloatField(db_column="Vitesse_b")  # Field name made lowercase.
vitesse_c = models.FloatField(db_column="Vitesse_c")  # Field name made lowercase.
ecart_type_b = models.FloatField(
    db_column="Ecart_type_b"
) 
ecart_type_c = models.FloatField(
    db_column="Ecart_type_c"
) 
type_site = models.CharField(
    db_column="Type_site", max_length=20
) 
longitude = models.FloatField(db_column="Longitude") 
latitude = models.FloatField(db_column="Latitude")  
Nombre_bulles = models.IntegerField(db_column="Nombre_bulles")
date_vidange = models.DateField(
    db_column="Date_vidange") 
class Meta:
    db_table = "site"

I've created a request to delete a row in "bulle" selected by the id_bulle (primary key). I'd like to get the "id_site" from this selected bulle that I delete in this request. Then, I need to count every "bulles" of the table that have this id_site. After that I would like to change the value of the column "Nombre_bulles" by the number found just before.

def DeleteBulle (request, id_bulle):
try:
    id_bulle
    param = Bulles.objects.get(pk=id_bulle)
    param.delete()
    print("Bulle supprimée")
 except:
    print("Cette bulle n'existe pas")
    return redirect('api_bulles_frontend')
 return redirect('api_bulles_frontend')

I don't know how to access the value of the Id_site of the "bulle" I'm deleting selected by its id.

I'm sorry for my english, I hope someone here can help me. Thanks !

I really don't know how I could do that, I can't find it on Internet.

CodePudding user response:

param.id_site.somethingFromTheClass

  • Related