[Fixed]-Django Models relations

1👍

After looking at the Models and explanation provided below the Book model the users field should have ForeignKey relationship with the BookUser model.

so Book model should look like

class Book(models.Model):
    isbn = models.CharField(max_length=13)
    title=models.CharField(max_length=500)
    description =models.TextField()
    author = models.CharField(max_length=200)
    userRating = models.CharField(max_length=1)
    users = models.ForeignKey(BookUser, null=True, blank=True)           

if you are using Postgresql and if you just need the pk list of booksInShelf and booksUnderCirculation then your BookUser model should look like

class BookUser(models.Model):
    email= models.CharField(max_length=254,primary_key=True)                 
    name = models.CharField(max_length=254)                  
    contact= models.CharField(max_length=12)
    imei = models.CharField(max_length=16)                
    address= models.TextField()            
    booksInShelf = models.ArrayField(models.IntegerField())        
    booksUnderCirculation = models.ArrayField(models.IntegerField())        

and if you wish to have the full information of booksInShelf and booksUnderCirculation (not just the pk but other information related to the book as well), then you need to define it as ManyToMany relation.

class BookUser(models.Model):
        email= models.CharField(max_length=254,primary_key=True)                 
        name = models.CharField(max_length=254)                  
        contact= models.CharField(max_length=12)
        imei = models.CharField(max_length=16)                
        address= models.TextField()            
        booksInShelf = models.ManyToMany(UserBook)
        booksUnderCirculation = models.ManyToMany(UserBook)

also rather than creating two ManyToMany fields in the BookUser model you can have two flags in your UserBook model called is_in_shelf and is_under_circulation. These fields would be BooleanField, you can check more about the model fields in Django Documentation here: https://docs.djangoproject.com/en/1.10/topics/db/models/#fields

0👍

This should do what you want :

class UserBook(models.Model):
    bookId = models.ForeignKey('Book')

Here a UserBook has a reference to a Book item, and severals users can have the same book, but it’s still a unique reference in you table Book.

Hope it helps

Leave a comment