简体   繁体   中英

How to compare objects in Django?

Hello I'm newbie in Django and programming also. Can someone explain me how to compare objects created by the same model?

  • product1
  • shop1
  • product1
  • shop2
  • product1
  • shop3

I want my app to do something if it finds more than one object with the same parameter - "product1" and ideally will be make an object like this:

  • product1
  • shop1
  • shop2
  • shop3

Model:

class ProductInShop (models.Model):
    product = models.ForeignKey(Product)
    shop = models.ForeignKey(Shop)

View:

def products(request):
    all_products = ProductInShop.objects.all
    return render_to_response('polls/products.html', {
        'all_products': all_products,
        })

Template:

{% for asd in all_products %}
    <li>{{ asd.product.name }}</li>
    <li>{{ asd.shop.name }}</li>
    </br>
{% endfor %}

You could compare the md5 of objects:

http://docs.python.org/2/library/hashlib.html

I think, that you can change your structure like this:

Model:

class Product(models.Model):
    ... all other fields
    shops = models.ManyToManyField(Shop)

View:

def products(request):
     all_products = Product.objects.all()
     return render_to_response('polls/products.html', {
        'all_products': all_products,
     })

Template:

{% for product in all_products %}
    <li>{{ product.name }}</li>
    {% for shop in product.shops.all() %}
        <li>{{ shop.name }}</li>
    {% endfor %}
    </br>
{% endfor %}

Update:

With your structure you can write following:

View:

def products(request):
    all_products = Product.objects.all()
    return render_to_response('polls/products.html', {
        'all_products': all_products,
    })

Template:

{% for product in all_products %}
    <li>{{ product.name }}</li>
    {% for productinshop in product.productinshop_set.all %}
        <li>{{ productinshop.shop.name }}</li>
    {% endfor %}
    </br>
{% endfor %}

but this will generate many queries to database. Maybe will be better if you'll create method in Product model:

def get_shops(self):
    return Shop.objects.filter(productinshop__product_id=self.pk)

And then in template:

{% for product in all_products %}
    <li>{{ product.name }}</li>
    {% for shop in product.get_shops %}
        <li>{{ shop.name }}</li>
    {% endfor %}
    </br>
{% endfor %}

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