Home python Need help with one to many. Django

Need help with one to many. Django

Author

Date

Category

Hello, in models.py I have:

class user (models.Model):
  user_id = models.CharField (max_length = 1000)
  def __str __ (self):
    return self.user_id
class messages (models.Model):
  mes = models.ForeignKey (user)

But I can’t figure out how to add many mes to one user . Can you explain or give a kick in the right direction?


Answer 1, authority 100%

Corrected your code a bit, and added comments for what’s what.

class User (models.Model):
  # the id field will be created automatically, so you don't need to create it yourself
  name = models.CharField (max_length = 20)
  def __str __ (self):
    return "user:" + self.name
class Message (models.Model):
  # this field is required to link to the user table
  user = models.ForeignKey (user, on_delete = models.CASCADE)
  # text of the user's message.
  text = models.CharField (max_length = 1000)
user1 = User.objects.create (name = "Andrey") # created a user
m1 = Message.objects.create (user = user1, text = "message text") # created a pair of messages
m2 = Message.objects.create (user = user1, text = "more message text")
# this way you can find all messages of a given user
messages = Message.objects.filter (user = user1)

Answer 2

For admin area

from .models import *
class messagesAdminInline (admin.TabularInline):
  model = messages
  extra = 2 # Number of fields
class userAdmin (admin.ModelAdmin):
  fields = [field.name for field in user._meta.fields]
  inline = [messageAdminInline]
  class Meta ():
    model = user
admin.site.register (user, userAdmin)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions