Problema con l'utilizzo della query in Django

Aug 31 2020

Quindi quello che sto cercando di ottenere è il seguente. L'utente può scegliere 3 categorie come mostrato nel codice.

All'interno di queste categorie possono aggiungere un numero qualsiasi di piante. A mio avviso: collezione Voglio che l'utente veda quanto segue:

COLLEZIONE

Category_selected_by_user

  • plant_1
  • plant_2
  • ....

Category_selected_by_user2

Quello che ottengo in questo momento è:

COLLEZIONE

Category_selected_by_user

Category_selected_by_user2

Category_selected_by_user3

quindi fondamentalmente questo è il codice in models.py:

class Plant_category(models.Model):
    """This class contains the users different categories"""
    CATEGORY_CHOICES = [
        ('Houseplant', 'Houseplant'),
        ('Succulents', 'Succulents'),
        ('Outdoor', 'Outdoor'),
    ]
    """Plural for multiple categories"""
    class Meta:
        verbose_name_plural = 'Categories'
        
    """Returns the above stated choices"""
    category = models.CharField(max_length=50, choices=CATEGORY_CHOICES)
    def __str__(self):
        return self.category

class Plant_name(models.Model):
    """This class contains the plant name that is housed within a certain category"""
    """Links the plant to one of the chosen categories"""
    category = models.ForeignKey(Plant_category, on_delete=models.CASCADE, related_name='plant_names')
    
    # Placeholder for connection with a plant database API
    plant = models.CharField(max_length=50)
    
    """Return the plant input from the user"""
    def __str__(self):
        return self.plant

questo è il codice in views.py:

def collection(request):
    """The page that opens the collection of plants"""
    plant_categories = Plant_category.objects.all().order_by('category')
    
    
    context = {
        'plant_categories': plant_categories,
    }
    
    return render(request, 'plntz_main/collection.html', context)

E questo è il codice in collection.html:

<ul>
    {% for category in plant_categories %}
        <h3>{{ category }}</h3>
        {% for name in plant_categories.plant_names.all %}
            <li>{{ name.plant }}</li>
        {% endfor %}
    {% empty %}
        <li>No category has been added yet.</li>        
    {% endfor %}

</ul>

Deve esserci qualcosa di sbagliato nei dati estratti per le piante all'interno della categoria. Non riesco a trovare la causa di questo.

Ad esempio, questi sono i dati dell'amministratore che sono stati aggiunti in Houseplant:

  • houseplant_1
  • houseplant_2

E questo è stato aggiunto sotto Succulente:

  • Cactus_1
  • Cactus_2

Risposte

Jonas Aug 31 2020 at 19:40

Imho questo causa il problema: non fai riferimento correttamente all'oggetto / set di query, quindi nessun dato viene reso dal frontend.

Il tuo contesto contiene l'oggetto plant_categoriesche dovrebbe essere ripetuto di conseguenza:

<ul>
{% for category in plant_categories %}
    <h3>{{ category }}</h3>

    # Refer to object within context
    {% for name in plant_categories %}

        <li>{{ name.plant }}</li> # Depending on what you would like to render you have to adapt here

    {% endfor %}
{% empty %}
    <li>No category has been added yet.</li>        
{% endfor %}

Puoi aggiungere un'istruzione print alla tua vista per controllare il set di query:

def collection(request):
"""The page that opens the collection of plants"""
plant_categories = Plant_category.objects.all().order_by('category')


context = {
    'plant_categories': plant_categories,
}

# Print for debugging
print(plant_categories)

return render(request, 'plntz_main/collection.html', context)