Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from Django Many To Many Field?

Can someone explain to me how to get data from a many to many field. My model:

class Subcat(models.Model):
    subcat_name = models.CharField(max_length=128,default='Unknown')
    active1 = models.BooleanField()
    variants = models.ManyToManyField('Variants')
    lang = models.ForeignKey('Lang',default=1)

    def __unicode__(self):
        return self.subcat_name

class Variants(models.Model):
    lang = models.ForeignKey('Lang')
    name  = models.CharField(max_length=256)
    descr = models.CharField(max_length=500,default='Unknown')

    def __unicode__(self):
        return self.name

class Lang(models.Model):
    name  = models.CharField(max_length=25)
    code  = models.CharField(max_length=5)

    def __unicode__(self):
        return self.name

In class Subcat user defines subcategory, default is on English language, for example:

subcat_name = "Museums"
active1 = 1
variants = Muzeji,...
lang = en

So the default language is English, and when I want English subcat it's easy to get

subcategory="Museums"
data= Subcat.objects.get(subcat_name=subcategory)

so my question is: when user uses another language for example

subcategory= "Muzeji"
data=?????

how can I make a query from that information that will return me id where subcat_name is Museums...

Can someone explain me in details How to get data from Many To Many fields or point me to some good tutorial...

like image 756
ivan Avatar asked Oct 31 '22 19:10

ivan


1 Answers

subcat= Subcat.objects.get(subcat_name=subcategory)
variant=subcat.variants.filter(name="Muzeji")
lang=variant.lang.name
  1. get the subcat object
  2. get the appropriate variant with name="Muzeji"
  3. now you can access directly to lang:

if you want to return id :

variant=subcat.variants.filter(name="Museums").values('id')
like image 164
slim_chebbi Avatar answered Nov 09 '22 09:11

slim_chebbi