Charles Smith
Charles Smith

Reputation: 3289

Check if Django Object in Many-to-Many Exists then Display Object Only

I have a list of tools that have a part added as a bundle. The bundle is listed as a part in a many-to-many field, so I need to iterate over the parts to see if the add-on product exists for the tool being displayed. If the part exists, then I want to display just the part itself. I've tried working it out with the code below and it does check if it exists, but prints out the queryset. I understand the .all() is the cause of this but I can't figure out how to check and then just display the single part. Thank you for your help.

{% for p in tool.parts.all %}
  {% if 'bp-01' %}
    <h3>Bundle Included:</h3>
    {{ p.model_number }}
    ...
  {% endif %}
{% endfor %}

Part Model

class Part(Timestamp):
    model_number = models.ForeignKey(ModelNumber)
    price = models.SmallIntegerField()
    title = models.CharField(max_length=250)
    slug = models.SlugField(help_text="slug-title-should-be-like-this")
    description = RichTextField()
    type = models.ForeignKey(Type, blank=True)
    category = models.ForeignKey(Category)

Tool Model

class Tool(Timestamp):
    model_number = models.ForeignKey(ModelNumber)
    price = models.SmallIntegerField()
    title = models.CharField(max_length=250)
    slug = models.SlugField(help_text="slug-title-should-be-like-this")
    description = RichTextField()
    type = models.ForeignKey(Type)
    category = models.ForeignKey(Category)
    parts = models.ManyToManyField(Part, blank=True, related_name="parts")

Model Number Model

class ModelNumber(models.Model):
    slug = models.SlugField(max_length=100, unique=True, help_text="slug-title-should-be-like-this")

    class Meta:
        verbose_name = 'Model Number'
        verbose_name_plural = 'Model Numbers'

    def __str__(self):
        return self.slug

Upvotes: 1

Views: 393

Answers (2)

AKS
AKS

Reputation: 19831

If you just have slug field on ModelNumber you can use {% if p.model_number.slug== 'bp-01' %} to check for the condition:

{% for p in tool.parts.all %}
  {% if p.model_number.slug == 'bp-01' %}
    <h3>Bundle Included:</h3>
    {{ p.model_number }}
    ...
  {% endif %}
{% endfor %}

Upvotes: 1

Hybrid
Hybrid

Reputation: 7049

Depending on how your ModelNumber model looks, you can compare the values with something like this:

{% for p in tool.parts.all %}
  {% if p.model_number.number == 'bp-01' %}
    <h3>Bundle Included:</h3>
    {{ p.model_number }}
    ...
  {% endif %}
{% endfor %}

This is assuming that ModelNumber looks something like this:

class ModelNumber(models.Model):
    number = models.CharField(max_length=20)
    ....

    def __str__(self):
        return self.number

Upvotes: 0

Related Questions