To convert a Django model instance to a dictionary that includes related foreign key instances, you can use the values() method with the select_related() method.

Here's an example:

# models.py
class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

# views.py
def book_detail(request, book_id):
    book = Book.objects.select_related('author').get(id=book_id)
    book_dict = book.__dict__
    author_dict = book.author.__dict__
    book_dict['author'] = author_dict
    del book_dict['_state']
    del author_dict['_state']
    return JsonResponse(book_dict)

In this example, we first use the select_related() method to fetch the related Author instance along with the Book instance. Then, we use the __dict__ attribute to convert the instances to dictionaries. We add the author_dict to the book_dict as a new key-value pair. Finally, we delete the _state attribute from both dictionaries to avoid serializing it in the response.

Note that this approach may not work if you have circular relationships or if you want to include many-to-many relationships. In those cases, you may need to use a more complex serialization library like Django REST Framework or write a custom serializer function.

django model instance to dict with foreign instance

原文地址: http://www.cveoy.top/t/topic/yLf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录