tags:

views:

42

answers:

1

I have one problem Looking below:

i have this model

class Shoes(models.Model):
    shop            = models.ForeignKey(Store, related_name="%(class)s")
    name            = models.ForeignKey(ShoesItem)
    size            = models.ManyToManyField(ShoesSize, help_text=_("Get useful sizes")) 
    price           = models.IntegerField() 

in my case i have models ShoesSize for store all ShoesSize and ShoesItem for store this Item

how can i gel all sizes and all shops from ShoesItem instance? there are (not full, for example):

class Store(models.Model):
    name            = models.CharField(max_length=255) 


class Item(models.Model):
    name            = models.CharField(max_length=255)
    brand           = models.ForeignKey(Brand, related_name="%(app_label)s_%(class)s")  
    sysname         = models.SlugField(max_length=255) 

    has_shop        = models.BooleanField(editable=False, default=False)
    description     = models.TextField(blank=True, verbose_name="Описание")
    color           = models.ManyToManyField(Color, blank=True, related_name='%(app_label)s_%(class)s')

and i get list of instances of Item models. After that I want get all available sizes and shops for all kind of items

+1  A: 

Use a reverse query by using the model name.

Get a ShoesItem:

shoes_item = ShoesItem.objects.all()[0]

Get ShoesSize objects for the ShoesItem via Shoes object:

sizes = ShoesSize.objects.filter(shoes__name=shoes_item)

Get Store objects for the ShoesItem via Shoes object:

shops = Store.objects.filter(shoes__name=shoes_item)

See more - Lookups that span relationships

For a queryset of ShoesItem:

shoes_items = ShoesItem.objects.filter(has_shop=True)
sizes = ShoesSize.objects.filter(shoes__name__in=shoes_items)
shops = Store.objects.filter(shoes__name__in=shoes_items)
sunn0