Django / Python - 在对象创建中使用ManyToMany字段

时间:2018-03-01 16:59:59

标签: python django django-models

有没有办法使用ManyToManyField在模型中创建对象?

以下是模型:

class Booking(models.Model):
    tour_ref = models.CharField(max_length=30)
    customers = models.ManyToManyField(Customer)

class Customer(models.Model):
    name = models.CharField(max_length=40)
    email = models.EmailField()

任务是创建一个新的Booking对象。但是,如何使用Customer表中的特定客户执行此操作? (我会通过电子邮件识别他们)。 (显然不止一个客户)。

非常感谢!

2 个答案:

答案 0 :(得分:3)

使用public class NoProjectRouteConstraint : IRouteConstraint { //all the controllers that are exempt from having project id in URL... public const string c_ExemptControllers = "account|filedownload|restful|ping|public"; private readonly string _controller; private readonly string _action; public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { var m = c_ExemptControllers.Split('|').ToList(); var controllerName = (values.ContainsKey("controller")) ? values["controller"].ToString() : ""; var actionName = (values.ContainsKey("action")) ? values["action"].ToString() : ""; var result = false; if (controllerName == string.Empty || actionName == string.Empty) return false; if (c_ExemptControllers.Contains(controllerName.ToLower())) { result = true; } return result; } } 将客户列表添加到新预订中:

add

或者您可以使用反向查找booking = Booking.object.create(tour_ref="ref") customers = list(Customer.objects.filter(email="email@mail.com")) booking.customers.add(customers) booking_set向特定客户添加预订:

create

答案 1 :(得分:0)

试试这个,

In [1]: Customer.objects.create(name="name_1",email="asd@asd.com")
Out[1]: <Customer: Customer object>

In [2]: Customer.objects.create(name="name_2",email="asd@asd.com")
Out[2]: <Customer: Customer object>

In [3]: Customer.objects.create(name="name_3",email="qwe@asd.com")
Out[3]: <Customer: Customer object>

In [4]: book = Booking.objects.create(tour_ref="reff_1")

In [5]: cus = Customer.objects.filter(email='asd@asd.com')

In [6]: for c in cus:
   ...:     book.customers.add(c)
   ...:     

In [7]: book.customers.all()
Out[7]: <QuerySet [<Customer: Customer object>, <Customer: Customer object>]>