Home > Enterprise >  Many to Many relationship - Returning "main.ModelName.None"
Many to Many relationship - Returning "main.ModelName.None"

Time:10-16

I am trying to return a few values from other models via a ManyToManyField. It's returning main.ModelName.None in the template.

The data is visible through the admin panel.

As a result, I am assuming the problem is linked to the views or the way I render the data in HTML.

I found a few post on the topic with the same problem but it seems there were dealing with an error message that I am not getting.

In my case, I just cant render the data.

Here is the code: models.py

class Supplier_Profile(models.Model):
    name = models.CharField('Supplier Profile', max_length=120, blank=True)
    user = models.ManyToManyField(User)

    def __str__(self):
        return str(self.name)

class Project(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(verbose_name="Name",max_length=100, blank=True)

    def __str__(self):
        return str(self.name) if self.name else ''

class Product(models.Model):
    project = models.ManyToManyField(Project, blank=True, related_name="available_products")
    name = models.CharField('Product Name', max_length=120, blank=True)

    class Meta:
        db_table='Product'
    def __str__(self):
        return str(self.name)

views.py

def show_product(request, product_id):
    products = Product.objects.get(pk=product_id)
    return render(request, 'main/show_product.html',{'products':products}) 

template

    <h6>Project Name</h6>
    {{ products.project }}

This returns main.Project.None

EDIT

Following Rohit's support, I used {{ products.project.all }} in my template.

This rendered the ugly <QuerySet [<Project: Project 1>]> which I then transformed into a loop to only return the project name Project 1.

<h6>Project Name</h6>
{% for Product in products.project.all %}

{{ products.name }}<br />

{%endfor%}

However, this solution does not seem to work for other fields.

As an example, using the same solution to get the supplier name ({{ products.project.all }}) would render <QuerySet [<Supplier_Profile: Supplier 2>, <Supplier_Profile: Supplier 3>]>.

In order to get rid of the <QuerysSet...> I used the following code:

template

{% for Product in products.supplier.all %}

{{ products.supplier }}

{%endfor%}

This leads me back to my old problem main.Supplier_Profile.None.

CodePudding user response:

Use {{ products.project.all }}

Reference: https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/

  • Related