简体   繁体   中英

Django DRF Model doesn't show foreign keys in admin panel

I have a model in my Django application for review. This model has two foreign keys to the product and user models. But when I go to the admin panel and try to add a new review I don't see the review models dropdown select for the foreign keys.

I'm expecting to see the foreign keys fields rendered in my admin panel as dropdown selects like in the blue box in the picture below.

Screenshot of my admin panel to add a new order object

But the admin panel doesn't show those fields. It only shows the name, rating, and comment fields.

Screenshot of my admin panel to add a new reivew object

Here is my review model.

class Reviews(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True),
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True),
    name = models.CharField(max_length=350, null=True, blank=True)
    rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, default=0)
    comment = models.TextField(null=True, blank=True)
    createdAt = models.DateTimeField
    _id = models.AutoField(primary_key=True, editable=False)

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

In your Reviews model, you have put a comma at the end of users and product fields. Remove the trailing comma at the end, as the fields are considered as tuple when a comma is present.

It should be:

user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)

Also, your createdAt field is not correct.

It should be:

createdAt = models.DateTimeField()

Try it like this, i removed comma from user and product field in the end, also i have added () in DateTimeField

class Reviews(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    name = models.CharField(max_length=350, null=True, blank=True)
    rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, default=0)
    comment = models.TextField(null=True, blank=True)
    createdAt = models.DateTimeField()

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