Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - How to fix manytomany field in django

How to make a one to many relationship in Django/Mysql?

I have an identical situation to this post, yet, my django returns errors on the admin page:

get() returned more than one order2pizza-- it returned 5!

order2pizza with that pizza already exists.

My mysql database have composite keys on a tertiary table to order and pizza to link multiple pizzas to an order.

models.py:

class Orders(models.Model):
    order_id = models.AutoField(primary_key=True)
    order_name = models.CharField(max_length=100, blank=True, null=True)


class Pizza(models.Model):
    Pizza= models.AutoField(primary_key=True)
    Pizza_name= models.CharField(max_length=50, blank=True, null=True)

class order2pizza(models.Model):
    order = models.ManyToManyField(Orders, models.DO_NOTHING, )
    pizza_id= models.IntegerField()
    class Meta:
        unique_together = (('order ', 'pizza_id'),)

question from:https://stackoverflow.com/questions/65909707/how-to-fix-manytomany-field-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A many-to-many relation can be expressed in two ways. First, you can manually specify a "join" model, like this:

class Orders(models.Model):
    order_name = models.CharField(max_length=255, blank=True)

class Pizza(models.Model):
    Pizza_name= models.CharField(max_length=255, blank=True)

class Order2Pizza(models.Model):
    order = models.ForeignKey(Order, models.CASCADE)
    pizza = models.ForeignKey(Pizza, models.CASCADE)
    class Meta:
        unique_together = ['order ', 'pizza']

This is useful if you want to put extra fields on the Order2Pizza model. A field named quantity would be very useful in your example.

The second option is to use a ManyToManyField. This will automatically create the join model for you:

class Orders(models.Model):
    order_name = models.CharField(max_length=255, blank=True)
    pizzas = models.ManyToManyField('Pizza', related_name='orders')

class Pizza(models.Model):
    Pizza_name= models.CharField(max_length=255, blank=True)

In your original question you put the ManyToManyField on the Order2Pizza model, which is nonsensical.

However, the source of your bug is probably your manual inclusion of several *_id fields. Don't do that. They will always be created automatically by Django and you should never have to specify them manually. Instead, try the two options above and see how they work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...