Search code examples
djangomany-to-many

Django many-to-many :how to get the id


I have models with manytomany field:

class Brand(models.Model):
    Company_Group = models.ManyToManyField(Company)

class Company(models.Model):
    Pref_Company_Name_Flg = models.CharField(u'Preferred Name Flag',max_length=255, default="")
    Pref_Company_Name = models.CharField(u'Preferred Name',max_length=255, default="")

I want to filter the id of brands in containing "company_instance"

brands = Brand.objects.all()
company_instance=company.objects.filter(id =company_id)
for brand in brands:
    for i in Brand.Company_Group.through.objects.filter(Company_Group = brand):
        print i.id

I have found the Similar problem as follows: click here

but Report errors :

Cannot resolve keyword 'Company_Group' into field. Choices are: brand, brand_id, company, company_id, id

then I try this way,also Report errors:

type object 'Brand' has no attribute 'Company_id'

Thanks andvance


Solution

  • You could just use the reverse relation from Company instance like,

    company = Company.objects.get(id=company_id)
    company.brand_set.all() #this would return all Brand instances
                            #with company instance.